std::formatter That Compiles: A Clang-Only Specialization Project
A custom formatter is a small contract: parse the spec, format the value. The contract is easy to state and easy to get wrong, because a bad spec can fail at compile time, at run time, or not at all, depending on how the format string reaches the formatter. This guide builds the project on the one toolchain where it runs end to end, Clang 18 with libstdc++ 13, and states plainly where the other compilers on this machine stop: GCC 16 with C++23 cannot assemble any real formatting code, and range formatting exists only on a GCC 16 frontend.
Written November 7, 2026 · Tested with GCC 16.2.0 · 15 min read
- The limit first: this guide is Clang-only
- The contract: parse, then format
- Part one: a formatter with a real spec
- Part two: a formatter that delegates the spec
The limit first: this guide is Clang-only
All four programs compiled with return code 0 and zero warnings, and all four ran with return code 0 at both standards. That is the whole tested ground for the working code. Two other toolchains on the same box do not reach it.
GCC 16.2.0 with C++23 cannot build any translation unit that uses real formatting machinery. The frontend accepts the code and the assembler rejects it:
/tmp/ccS2KDId.s:24520: Error: unknown pseudo-op: `.base64'
/tmp/ccS2KDId.s:42192: Error: unknown pseudo-op: `.base64'
The compile returns 1. The cause is the system assembler, GNU Binutils 2.42, which does not know the pseudo-op that GCC 16 emits for formatting code. A newer Binutils, or a different build host, removes the block.
GCC 16 with C++20 does build the two formatter programs, but the binaries need the extracted GCC 16 library on the search path at run time. With the path set, both ran with return code 0. The 2026-11-06 probe showed the same binaries failing without it, with GLIBCXX_3.4.35 not found. GCC 13.3.0 builds and runs the two formatter programs at both standards, but it has no range formatting at all, which the range section shows.
One more absence shapes the whole page. The C++23 print header does not exist on Clang 18 with libstdc++ 13:
print_check.cpp:1:10: fatal error: 'print' file not found
So every example here goes through std::format and its relatives, never through the print header. A well-known Medium tutorial on building a universal printer with custom formatters prints exclusively through that header, which means its code cannot even compile on the two toolchains this guide can actually run on. That tutorial is the baseline this guide does not re-teach; the last section says exactly what it covers and what this tutorial adds.
The contract: parse, then format
A formatter specialization is a type that meets two named requirements, BasicFormatter and Formatter. The reference page for the formatter class template states the shape, and the two requirement pages state the contract.
BasicFormatter requires the type to be semiregular: default constructible, copy constructible, copy assignable, destructible, and swappable. It also requires a parse member that takes a parse context, reads the format spec for the argument type until the first unmatched character, stores the parsed specifiers in the formatter object, throws std::format_error unless the whole range was parsed or the unmatched character is }, and returns an iterator past the end of the parsed range.
Formatter adds the format member. It takes the value and a format context, writes the output to the context output iterator, and returns an end iterator for the output range. It must be able to format both const and non-const arguments, which in practice means taking the value by const reference. The output may only depend on the value, the locale, the spec range from the last parse call, and other format arguments reached through the context.
A type with no enabled specialization has a disabled formatter: a complete type that meets neither requirement, and for which the default, copy, and move constructibility and assignability traits are all false. That is why formatting a type with no specialization is a compile error, not a silent fallback: the checker finds a deleted default constructor and reports that a formatter must be specialized for each type being formatted. The range section shows that error in full.
The class template itself is declared, since C++20, as a template over a type and a character type defaulting to char. The standard ships specializations for characters, strings, arithmetic types, nullptr_t, and void pointers. Formatters for other pointers and pointers to members are disabled, and specializations that would need an encoding conversion, such as formatting a wide character with a narrow character type, are disabled too.
Since C++23, a formatter for a string or character type is debug-enabled: it provides a set_debug_format member that makes it format values escaped and quoted, as if the spec parsed by the last parse call were ?. The debug section below tests exactly that spec, and the result depends on the library version in a way that surprises.
Part one: a formatter with a real spec
The first program follows the reference page example in shape: a string view type with a formatter that accepts one optional flag, #, and quotes the value when the flag is present. The code below is the exact file that ran, with the example value kept short so the quoting is visible:
// quotable.cpp — QuotableString-style formatter (reference example shape):
// parse accepts an optional '#' specifier, throws std::format_error otherwise;
// format writes via std::quoted when quoted.
#include <format>
#include <string>
#include <string_view>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <iostream>
struct QuotableString : std::string_view {};
template <>
struct std::formatter<QuotableString, char> {
bool quoted = false;
constexpr auto parse(std::format_parse_context& ctx) {
auto it = ctx.begin();
if (it != ctx.end() && *it == '#') { quoted = true; ++it; }
if (it != ctx.end() && *it != '}') throw std::format_error("invalid spec");
return it;
}
auto format(const QuotableString& s, std::format_context& ctx) const {
std::ostringstream out;
if (quoted) out << std::quoted(std::string(s));
else out << s;
return std::ranges::copy(out.str(), ctx.out()).out;
}
};
int main() {
QuotableString q{"hello \"world\""};
std::cout << std::format("{}", q) << "\n";
std::cout << std::format("{:}", q) << "\n";
std::cout << std::format("{:#}", q) << "\n";
// Invalid spec with a LITERAL format string is a compile-time error
// (the library consteval-checks parse, and the throw is not a constant
// expression), so the runtime path uses vformat with a runtime string.
try {
std::string fs = "{:z}";
std::cout << std::vformat(fs, std::make_format_args(q)) << "\n";
std::cout << "no-throw BAD\n";
} catch (const std::format_error& e) {
std::cout << "format_error ok: " << e.what() << "\n";
}
return 0;
}
The output is identical at C++20 and C++23, and identical on Clang 18 and on GCC 13 and GCC 16 at C++20:
hello "world"
hello "world"
"hello \"world\""
format_error ok: invalid spec
Three details carry the lesson. First, the empty spec and the no-spec form behave the same: both print the value unquoted. The flag only changes the output when it is present. Second, the quoting is done by the standard quoted manipulator, which escapes the inner quotes and wraps the whole value. The formatter does not hand-roll escaping. Third, parse throws std::format_error with the message invalid spec when it meets a character it does not accept, and that throw carries text written in the specialization.
Part two: a formatter that delegates the spec
The second program is the pattern the first one does not teach: a formatter for a composite type that hands its whole spec to a formatter for a member type. The type is a point with two doubles, and the formatter holds a formatter for double and delegates parsing to it:
// point.cpp — formatter delegating the spec to an underlying formatter<double>.
// Tests: no-spec, ".2f" delegation, invalid spec -> std::format_error.
#include <format>
#include <string>
#include <iostream>
struct Point { double x, y; };
template <>
struct std::formatter<Point, char> {
std::formatter<double, char> under;
constexpr auto parse(std::format_parse_context& ctx) {
return under.parse(ctx);
}
auto format(const Point& p, std::format_context& ctx) const {
auto out = ctx.out();
*out++ = '(';
out = under.format(p.x, ctx);
*out++ = ',';
*out++ = ' ';
out = under.format(p.y, ctx);
*out++ = ')';
return out;
}
};
int main() {
Point p{1.23456, 7.891};
std::cout << std::format("{}", p) << "\n";
std::cout << std::format("{:.2f}", p) << "\n";
std::cout << std::format("{:>8.1f}", p) << "\n";
// Literal "{:z}" would be a compile-time error (consteval parse check),
// so the runtime path uses vformat with a runtime string.
try {
std::string fs = "{:z}";
std::cout << std::vformat(fs, std::make_format_args(p)) << "\n";
std::cout << "no-throw BAD\n";
} catch (const std::format_error& e) {
std::cout << "format_error ok: " << e.what() << "\n";
}
return 0;
}
The output, again identical at both standards on Clang 18:
(1.23456, 7.891)
(1.23, 7.89)
( 1.2, 7.9)
format_error ok: format error: failed to parse format-spec
The third line is the point of the whole program. The width of 8 and the precision of 1 apply to each member separately, not to the whole (x, y) text. The first member prints right-aligned in 8 columns, then the comma and space, then the second member right-aligned in 8 columns. Anyone who writes a delegating formatter expecting the width to frame the composite text will get a surprise, and the surprise is silent: the program compiles and runs, and the output is wider than expected. Delegation means the member formatter owns the spec, including the width.
The invalid-spec line shows the other half of delegation. The error message is not the custom text from part one. It is the message from the underlying double formatter: "format error: failed to parse format-spec". The delegating parse never sees the bad character; the member formatter rejects it first, and its message is the one that surfaces. Delegation passes the spec language and the diagnostics together: the member formatter decides both.
The error split: compile time or run time
The two programs above each test an invalid spec twice over: once as a literal format string, once as a runtime-built string. The results differ, and the difference is the most useful fact in this tutorial.
A literal format string is checked at compile time. The library checks the format string in a constant-evaluated context, which runs parse during compilation. The parse in part one throws on an unmatched character, and a throw is not a constant expression, so the check fails and the compile fails. This run confirmed it with a small file that formats a quoted string with the literal spec {:z}:
litz.cpp:20:30: error: call to consteval function 'std::basic_format_string<char, QuotableString &>::basic_format_string<char[5]>' is not a constant expression
The compile returns 1. There is no binary and no run. That is the correct outcome for a typo in a literal spec: the mistake is caught before the program exists.
A runtime-built format string skips that check. std::vformat takes a plain string, so the spec is parsed when the program runs, and a bad spec throws std::format_error, which the program can catch. That is why both programs above build the bad spec in a string variable and wrap the call in a try block. The two paths give two different messages for the same bad spec: the quoted-string formatter throws its own invalid spec, and the delegating formatter surfaces the double formatter report "format error: failed to parse format-spec". The lesson is practical: if a spec only ever appears as a literal, a mistake is a build break; if a spec is ever built at run time, from user input or a config file, the same mistake is an exception the program must handle.
Writing somewhere else: format_to and friends
std::format returns a string. The rest of the formatting family writes somewhere else, and the second pair of programs in this tutorial exercises three of them: format_to, format_to_n, and formatted_size.
// format_to / format_to_n / formatted_size under Clang 18 + libstdc++ 13.
#include <array>
#include <format>
#include <iostream>
#include <string>
int main() {
// format_to into a string via back_inserter
std::string s;
std::format_to(std::back_inserter(s), "id={} name={}", 42, "ada");
std::cout << "format_to: [" << s << "]\n";
// format_to_n into a fixed buffer, truncated: returns out + size (full size)
std::array<char, 8> buf{};
auto res = std::format_to_n(buf.begin(), buf.size() - 1, "value={}", 123456789);
*res.out = '\0';
std::cout << "format_to_n: [" << buf.data() << "] size=" << res.size
<< " truncated=" << (static_cast<std::size_t>(res.size) > buf.size() - 1 ? "yes" : "no") << "\n";
// formatted_size: size without writing
std::size_t n = std::formatted_size("x={} y={}", 7, 3.25);
std::cout << "formatted_size: " << n << "\n";
// format_to with a custom formatter result reused: format the same value twice
std::string t;
std::format_to(std::back_inserter(t), "{:.2f}|{:.2f}", 1.234, 5.678);
std::cout << "format_to floats: [" << t << "]\n";
return 0;
}
The output, identical at both standards:
format_to: [id=42 name=ada]
format_to_n: [value=1] size=15 truncated=yes
formatted_size: 10
format_to floats: [1.23|5.68]
The format_to_n line is the one to read twice. The buffer holds 8 characters, and the call is told it has room for 7 plus a terminator. The value 123456789 makes the full text value=123456789, which is 15 characters. Only value=1 fits, so the buffer holds 7 characters and the returned size is 15, the full size that would have been written, not the 7 that were. The truncated flag is a comparison of that full size against the room available. Any code that checks only the returned iterator and never looks at the size will think the write succeeded. The size is the signal.
formatted_size answers the same question without writing anything: the text x=7 y=3.25 is 10 characters, and that is what it returns. The float line shows the custom formatters from the earlier sections working through format_to unchanged: the same :.2f spec, the same output, written into a string instead of returned as one.
Chrono types format for free
Durations and time points already have formatters in the standard library, so no specialization is needed for them. The last program in this tutorial formats a duration four ways and a time point two ways:
// chrono formatting under Clang 18 + libstdc++ 13 (std::format, not the print header).
#include <chrono>
#include <format>
#include <iostream>
int main() {
using namespace std::chrono_literals;
std::cout << "duration 90s: [" << std::format("{}", 90s) << "]\n";
std::cout << "duration 1500ms: [" << std::format("{}", 1500ms) << "]\n";
std::cout << "duration hms: [" << std::format("{:%H:%M:%S}", 3661s) << "]\n";
std::cout << "duration %Q %q: [" << std::format("{:%Q %q}", 42min) << "]\n";
auto now = std::chrono::system_clock::now();
std::cout << "sys_time default: [" << std::format("{}", now) << "]\n";
std::cout << "sys_time Y-m-d: [" << std::format("{:%Y-%m-%d}", now) << "]\n";
return 0;
}
The output, identical at both standards except for the clock reading:
duration 90s: [90s]
duration 1500ms: [1500ms]
duration hms: [01:01:01]
duration %Q %q: [42 min]
sys_time default: [2026-11-07 14:23:14.286722565]
sys_time Y-m-d: [2026-11-07]
The default duration form prints the value with its unit suffix, 90s and 1500ms, with no scaling to a larger unit. The chrono spec language supplies the rest: %H:%M:%S turns 3661 seconds into 01:01:01, and %Q %q splits a duration into its count and its unit, 42 min. The time point lines show the two ends of the same choice: the default form prints the full timestamp with nanosecond precision, and %Y-%m-%d prints the date alone. The clock reading in the default line is whatever the clock reads when the program runs; the C++20 run read 14:23:14 and the C++23 run, about two seconds later, read 14:23:15. The date is stable across runs on the same day. The rest of the line is not a value to copy; it is a shape to expect.
Ranges: what Clang cannot do, and what a GCC 16 frontend says
Range formatting is C++23, and it belongs to GCC 16 alone. Clang 18 with libstdc++ 13 has no range formatter at all: the feature-test macro for format ranges is undefined, the name range_formatter is unknown, and formatting a vector is a compile error. The diagnostic names the missing piece directly:
error: static assertion failed due to requirement 'is_default_constructible_v<std::formatter<std::vector<int, std::allocator<int>>, char>>': std::formatter must be specialized for each type being formatted
GCC 13 is in the same position: no range formatting, the same static assertion. So the range part of this guide cannot be a compiled-and-run program on the Clang toolchain. It is a set of frontend verdicts from GCC 16 at C++23, checked one spec at a time with syntax-only compiles, because a full compile dies on the assembler wall. Twelve specs were checked this way, and the split is eight accepted and four rejected.
The accepted specs: the default form and the n form on a plain vector of integers, the debug form ? on a plain string, the default and n forms on a custom range type that inherits the range formatter helper, the default and m forms on a vector of pairs, and the default form on a nested vector of integers. The rejected specs, each with the exact message from the library:
format error: 'm' specifier requires range of pairs or tuples of two elements
format error: 's' specifier requires range of character types
format error: '?' is allowed only in combination with 's'
The m message appears for the m spec on a vector of integers and on the custom range type: m is the map style, with { brackets and each element formatted as a pair, so it is only valid when the element type is a pair or a two-element tuple. The s message appears for the s spec on a vector of integers: s formats the range as a string, so it needs a range of characters. The ? message appears for a bare ? on a vector of integers: a lone ? is not a range type at all, and it is only allowed together with s, as ?s, which formats the range as an escaped string. The reference page for the range formatter helper states all three rules, and the frontend verdicts match the page exactly.
The custom range type used in those checks is a struct holding a vector of integers, with a formatter that inherits the range formatter helper for integers and forwards the range to it:
struct IntList {
std::vector<int> data;
};
template <>
struct std::formatter<IntList, char> : std::range_formatter<int, char> {
auto format(const IntList& l, std::format_context& ctx) const {
return std::range_formatter<int, char>::format(l.data, ctx);
}
};
The helper supplies parse, the bracket and separator handling, and the underlying element formatter, so the specialization only needs to hand over its range. The inheritance pattern itself is accepted by the GCC 16 frontend; only the m spec on the integer range fails, at parse time. Two limits stay open and are stated as open: no runtime output exists for any range example, because no binary can be built, and the runtime fate of the s and ?s specs on a vector of integers through a runtime-built format string is still untested for the same reason.
The debug spec on a plain string belongs in this section too, because it splits the two libraries. On Clang 18 with libstdc++ 13, formatting a string with the ? spec is a compile error at both standards: the library there predates the C++23 debug format. On the GCC 16 frontend at C++23, the same spec is accepted. A guide that teaches the debug spec as portable across these two toolchains would be wrong on the first one.
What the Medium baseline covers, and what this tutorial adds
The baseline for this guide is a Medium tutorial that builds a universal printer from custom formatters, in eight parts: primitives, enums converted to strings, reflection emulation for structs, containers, maps, tuples and pairs, container adapters, and a grand finale with a composed example. It is worth naming what it does, because this tutorial deliberately does not repeat it.
The tutorial prints everything through the C++23 print header, which does not exist on the toolchains this guide runs on, so its code cannot compile here. Every formatter in it inherits the string formatter and never overrides parse, so no spec is ever handled and no invalid spec is ever diagnosed. Its ranges are hand-rolled with a concept and a loop, not the standard range formatter helper, so the n, m, s, and ?s range specs never appear. It has no debug format, no compiler matrix, no feature-test macros, and no executed verification of its own: the outputs are asserted in the text and the execution is left to a linked playground. Its reflection emulation is capped at three fields by hand-written cases, with a comment to add more cases for four, five, and six fields.
This tutorial adds what that list leaves out, and nothing else: a parse that accepts a real flag and throws on anything else; a delegating formatter that hands its spec to a member formatter, with the per-member width behaviour shown; the compile-time versus runtime split for invalid specs, with both messages quoted; the output functions that write somewhere other than a returned string, with the truncation signal explained; chrono formatting that needs no specialization; and the range verdicts with the exact rejection messages, checked one spec at a time. It does not add a universal printer, a reflection trick, or a map formatter, because those belong to the baseline and this tutorial has nothing tested to add to them.
Compiler matrix
The matrix below is the whole tested ground for this tutorial, in one place. PASS means compiled with return code 0 and zero warnings and ran with return code 0. A frontend verdict means the syntax-only check passed or failed as stated, with no binary built.
| Compiler | Standard | Formatter project | Range formatting |
|---|---|---|---|
| Clang 18.1.3 | C++20 | PASS | Not available |
| Clang 18.1.3 | C++23 | PASS | Not available |
| GCC 13.3.0 | C++20 | PASS | Not available |
| GCC 13.3.0 | C++23 | PASS | Not available |
| GCC 16.2.0 | C++20 | PASS with library path | Not available |
| GCC 16.2.0 | C++23 | Assembler wall | Frontend verdicts only |
The formatter project column covers the quoted-string and point programs. The range column covers the twelve isolated spec checks: eight accepted and four rejected on the GCC 16 frontend at C++23, and unavailable everywhere else. No result from another compiler, another library, or another platform is claimed. MSVC and libc++ floors are not stated here, because neither was tested and no version floor was read from a primary during this run.
Frequently asked questions
Can I use this guide with GCC?
For the formatter project, yes at C++20: GCC 13 runs it as-is, and GCC 16 needs the extracted library on the search path at run time. At C++23, GCC 16 cannot assemble formatting code, so the working toolchain is Clang 18. For range formatting, only the GCC 16 frontend at C++23 gives verdicts, and only as syntax-only checks.
Why does an invalid spec sometimes fail the build and sometimes throw?
A literal format string is checked at compile time, so a bad spec is a build break. A format string built at run time is parsed when the program runs, so a bad spec throws std::format_error. The same spec, the same formatter, two different failure modes. Code that ever builds a spec at run time must catch the exception.
Does the width in a delegating formatter apply to the whole value?
No. The member formatter owns the spec, so the width applies to each member the formatter writes. A point formatted with a width of 8 prints each coordinate in 8 columns. If the whole composite text needs framing, the formatter has to do that itself, by formatting the members into a temporary string first and then applying the width to that string.
Why is there no range output in this tutorial?
Clang 18 and GCC 13 have no range formatting, and GCC 16 at C++23 cannot get past the assembler. The page gives frontend verdicts and exact rejection messages instead, and says plainly that they are frontend verdicts. Runtime output for ranges waits on a newer assembler or a different build host.
What does the debug spec do on a string?
It formats the value escaped and quoted, as if the spec were ?. On the GCC 16 frontend at C++23 it is accepted. On Clang 18 with libstdc++ 13 it is a compile error at both standards, because that library predates the C++23 debug format. The spec is standard; the support is not uniform.
Related guides on this site
- GCC 16.2: std::print, ranges::to, and from_range — What Actually Compiles, and the Macro That Does Not Exist
- A thread that stops itself cleanly (std::jthread)
- Fix C++ "no match for 'operator<<'" — Streaming a User-Defined Type and a std::vector of It to std::cout
- Fix C++ "invalid conversion from 'const char*' to 'char*'" — Add const, Copy the Text, or Own It in std::string
Sources
- cppreference, std::formatter — the class template declaration since C++20, the enabled and disabled specializations, the debug-enabled rule since C++23, the standard specializations for library types including ranges and pairs, and the quoted-string example this guide follows in shape.
- cppreference, BasicFormatter — the semiregular requirement and the
parsecontract: parse until the first unmatched character, throwstd::format_errorunless the whole range was parsed or the unmatched character is}, store the spec, return an iterator past the parsed range. - cppreference, Formatter — the
formatcontract: write to the context output iterator, return an end iterator, format const and non-const arguments, and depend only on the value, the locale, the last parsed spec, and other format arguments. - cppreference, std::range_formatter — the C++23 helper for range specializations, the range format spec syntax, the
noption that drops the brackets, themrule for pairs and two-element tuples, thesand?srules for character ranges, and theset_separator,set_brackets, andunderlyingmembers. - Medium, The Ultimate C++23 Guide: Creating a Universal Printer with std::formatter — the baseline this guide does not re-teach: eight parts from primitives to a grand finale, all printing through the C++23 print header, with formatters that inherit the string formatter and never override
parse, hand-rolled ranges, and reflection capped at three fields.
Keep Exploring
Seven tips and seven puzzles so far, each one a short runnable example with the fix explained.
Paste an AddressSanitizer, UBSan, or ThreadSanitizer report and get the bug, the file and line, and the fix \u2014 in plain language.
C++20 and C++23 features, migration paths, and measured trade-offs.
The full C++ hub \u2014 language basics, the standard library, coroutines, and measured comparisons.
Paste a [Service] section and get a plain-language verdict on every sandboxing setting it finds.