C++ Reference ยท Strings and I/O
C++ custom formatters (std::formatter)
Reference for specializing std::formatter: make your own types work with std::format and std::print, parse custom specs, reuse built-in formatters.
std::format and std::print can format a user-defined type once you specialize std::formatter<T>. The specialization has two member functions: parse, which reads the part of the format string after the colon, and format, which writes the value into the output.
The easiest way to write one is to inherit from an existing formatter, usually std::formatter<std::string_view> or std::formatter<int>. You convert your object to something simple, then let the base class apply width, alignment and fill. You only write parse when you want to support new specification letters of your own.
template<> struct std::formatter<Point> : std::formatter<std::string> { template<class FormatContext> auto format(const Point& p, FormatContext& ctx) const { return std::formatter<std::string>::format( std::format("({}, {})", p.x, p.y), ctx); } };
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Syntax
template<> struct std::formatter<T, char> { constexpr std::format_parse_context::iterator parse(std::format_parse_context& ctx); template<class FormatContext> typename FormatContext::iterator format(const T& value, FormatContext& ctx) const; };
| Name | Description |
|---|---|
ctx (in parse) |
Gives the range of the format string after the colon. ctx.begin() is the first character of the spec, and the range ends at the closing } (or at the end of the string). |
ctx (in format) |
Gives the output iterator through ctx.out(), and access to other arguments for dynamic widths. |
value |
The object to print. Taking it by const& is the usual choice. |
Returns: parse must return an iterator to the end of the spec (the position of the }). format must return the output iterator after the last character written, which is what std::format_to(ctx.out(), ...) returns.
Errors / undefined behavior: parse signals a bad specification by throwing std::format_error; with a literal format string this becomes a compile-time error because parse is constexpr. A format that does not return the output iterator it received is undefined behavior.
Usage notes
- Specialize in namespace scope with
template<> struct std::formatter<T>. Specializing a standard template for your own type is allowed. - Inheriting is the shortcut. Deriving from
std::formatter<std::string_view>gives you the full standard string mini-language (width, fill, alignment, precision) for free. Call the baseformatwith your text. - Call the base
parseif you add features on top of an inherited one; otherwise the base never sees the specification. When you write your ownparse, handle the case where the spec is empty ({}). - Make
formata template on the context type (template<class FormatContext>), not a function takingstd::format_context&.std::formatof a single value happens to usestd::format_context, but range, tuple and nested formatting use other context types. A non-templateformatcompiles for plain values and then fails when you print astd::vector<Point>. formatshould beconst. It lets the formatter be used for const objects and is what the standard requires from C++23 on.parseruns at compile time for literal format strings, so it can reject bad specs early. It must beconstexprfor that to work.- Ranges of your type work automatically once
Tis formattable. Elements use the element formatter, but a formatter derived from a string formatter prints its text quoted inside a range (["(1, 2)", "(5, 6)"]) because ranges switch such elements to the debug form. Writeformatyourself, as in the second example, to avoid the quotes. std::range_formatter(C++23) helps build formatters for your own container types.- Not
operator<<. Anoperator<<for a type is not used bystd::format. Thefmtlibrary offers anostream_formatteradapter; the standard does not. - Debug and nested use. To format members with the user's own flags, forward the spec to a stored
std::formatter<Member>(call itsparse, then itsformat).