skip to content

How do you make a C++ Money type printable with std::format, and what must the std::formatter specialization's parse and format members do?

level: seniorimportance: should knowfreq 42%

answer

  1. specialize the standard class template
  2. parse reads up to the closing brace
  3. format must be a const member
  4. inherit to reuse width and fill
  5. operator<< is not enough

basics

~20 s

Specialize std::formatter<Money>. Its parse member reads the format specification and returns an iterator to the closing brace, and its const format member writes the value to ctx.out() and returns the end iterator. Inheriting from std::formatterstd::string reuses width, fill and alignment.

solid answer

~40 s

You write `template<> struct std::formatter<Money>`, which the standard allows for a program-defined type. It needs two members. `parse(std::format_parse_context&)` is `constexpr`, reads the specification after the colon and returns an iterator to the `}`; anything it cannot consume is a `std::format_error`, which becomes a compile error for a literal format string because `parse` runs inside the consteval check. `format(const Money&, std::format_context&) const` writes to `ctx.out()`, usually with `std::format_to`, and returns the iterator past the output. It must be `const`: a non-const `format` makes the type not formattable. The easy path is to inherit from `std::formatter<std::string>` or `std::formatter<std::string_view>`, keep its `parse`, build the text, and call the base `format`, so `{:>12}` works for `Money` for free.

code

cpp · 26 lines
cpp
#include <cstdint>
#include <format>
#include <iostream>
#include <string>

struct Money {
    std::int64_t cents;
};

// Reuse the string formatter's fill, align and width parsing.
template <>
struct std::formatter<Money> : std::formatter<std::string> {
    auto format(const Money& m, std::format_context& ctx) const {
        std::int64_t abs = m.cents < 0 ? -m.cents : m.cents;
        std::string text = std::format("{}${}.{:02}", m.cents < 0 ? "-" : "",
                                       abs / 100, abs % 100);
        return std::formatter<std::string>::format(text, ctx);
    }
};

int main() {
    Money balance{-123456};
    std::cout << std::format("[{}]", balance) << '\n';
    std::cout << std::format("[{:>12}]", balance) << '\n';
    std::cout << std::format("[{:*<12}]", Money{705}) << '\n';
}

go deeper

for a junior

Recall that a user type needs a std::formatter specialization, and that operator<< does not make it work with std::format.

for a middle

Explain parse and format: parse consumes the spec up to the brace, format writes to ctx.out() and returns the iterator.

for a senior

Show the traps: const format, constexpr parse inside the compile-time check, reusing a standard formatter, and money held as integer cents.

for a principal

Decide which domain types get formatters, which specification grammar each accepts, and how they stay consistent with existing stream output.

## What std::format needs from your type `std::format` looks up `std::formatter<T, char>` for every argument type `T`. The standard library specializes it for arithmetic types, strings, pointers, `bool`, chrono types and, since C++23, ranges and tuples. For your own `Money` there is no specialization, so `std::format("{}", balance)` fails to compile with a message that the type is not formattable. Defining `operator<<` does **not** help: `std::format` never falls back to streams. ## The two members A specialization must meet the standard's **BasicFormatter** requirements. In practice that means a default-constructible, copyable class with: 1. **`parse`**: `constexpr auto parse(std::format_parse_context& ctx)`. `ctx.begin()` points at the specification after the colon, and the range ends at the end of the whole format string. `parse` consumes what it understands, stores the options in the formatter, and returns an iterator to the closing `}`. If it meets something it cannot handle, the requirement is to throw `std::format_error`. 2. **`format`**: `auto format(const Money& m, std::format_context& ctx) const`. It writes the value to `ctx.out()` according to the options `parse` stored and returns the iterator past the output. Two details catch people out: - **`format` must be `const`.** The requirements call `format` on a possibly-const formatter. On libc++ a non-const `format` fails with "the supplied type is not formattable", which is far from where the mistake is. - **`parse` runs at compile time.** For a literal format string, the consteval `std::format_string` constructor calls your `parse` during compilation, so a `parse` that is not `constexpr`, or that rejects the spec, becomes a compile error at the call site. A `parse` that returns `ctx.begin()` unconditionally accepts `{}` but turns `{:>12}` into a compile error, since the `>12` is left unconsumed. ## Reusing a standard formatter Most user types want the standard width, fill and alignment. Inherit from a standard formatter and keep its `parse`: ```cpp template <> struct std::formatter<Money> : std::formatter<std::string> { auto format(const Money& m, std::format_context& ctx) const { std::string text = /* "-$1234.56" */; return std::formatter<std::string>::format(text, ctx); } }; ``` Now `std::format("[{:>12}]", balance)` right-aligns the money text in twelve columns, exactly as it would a string. The cost is one temporary string per call, which a hot path can avoid by writing the digits straight to `ctx.out()` with `std::format_to`. Inheriting from `std::formatter<std::int64_t>` would instead apply numeric options to a raw number, which is wrong for a currency. ## Writing your own specification When a type has its own options, `parse` walks the characters itself: - read optional flags, such as a `c` for cents-only or an `s` for a currency symbol, and store them in members; - stop at `}` and return that iterator; - throw `std::format_error` with a clear message on anything else. Keep the grammar small and document it, because every caller's format string is checked against it. ## Design choices for Money | Decision | Recommended | Why | |---|---|---| | Storage | integer cents, such as `std::int64_t` | a `double` cannot represent most cent values exactly | | Negative values | sign before the symbol, as in `-$1234.56` | integer division and `%` keep the sign on both parts | | Width and fill | inherit a string formatter | callers already know the standard specification | | Locale grouping | only when the caller asks | `std::format` is locale-independent by default | Split the cents with care: for `-123456`, `/ 100` gives `-1234` and `% 100` gives `-56`, so format the absolute value and add the sign once. ## Common mistakes - Declaring `format` non-const, and getting an error about formattability instead of about constness. - Forgetting `constexpr` on a hand-written `parse`, which then cannot run inside the compile-time check. - Specializing for a standard type, such as `std::vector<int>`: the standard only allows specializations that depend on a program-defined type. - Calling `std::format` inside `format` and returning a string, instead of writing to `ctx.out()` and returning the iterator. - Assuming `operator<<` makes a type formattable: it does not, and C++ has no standard bridge from streams to `std::format`. ## Testing a formatter A formatter is small but sits on every log line that mentions the type, so it deserves a few direct tests: - the default field `{}` for a positive value, a negative value, zero and a value under one unit (`Money{5}` must print `$0.05`, not `$0.5`); - every option the formatter accepts, including width and fill if it inherits them; - a `static_assert(std::formattable<Money, char>)` (C++23) next to the specialization, so a later edit that drops `const` from `format` fails right there. The concept checks `format` against an unspecified context type, so declare `format` as a template on the context type (`template <class FormatContext> auto format(const Money&, FormatContext&) const`); on libc++ a `format` that takes only `std::format_context&` works with `std::format` but fails the concept.

  • What happens if the formatter's parse just returns ctx.begin() and a caller writes {:>12}?
    For a literal format string the call fails to compile. The consteval `std::format_string` constructor runs `parse`, which leaves `>12` unconsumed, so the replacement field never reaches its closing brace and libc++ raises "The replacement field misses a terminating '}'" during constant evaluation. Through `std::vformat` it would throw `std::format_error` instead.
  • Why not inherit Money's formatter from std::formatter<double>?
    You would format a `double` built from integer cents, which reintroduces binary rounding, and callers could request specs that make no sense for money, such as `e` or `a`. Inheriting from a string formatter keeps only the layout options and leaves the digits under your control.

  • Defining operator<< for Money is enough for std::format
  • The format member can be non-const because it writes output
  • parse runs only at run time, so it need not be constexpr
  • You may specialize std::formatter for std::vector<int> in your project
  • Inheriting from std::formatter<double> is the right way to print money

Assumes C++20 std::formatter; the const requirement on format is in the C++23 wording, and ranges became formattable in C++23.