Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::formatter: a type’s formatting contract

A std::formatter<T, charT> specialization defines how a format specification is parsed and how a T value is written.

Version: C++23

Syntax

template<class T, class CharT = char>
struct std::formatter;

// A usable specialization provides conceptually:
constexpr auto parse(std::basic_format_parse_context<CharT>& ctx);
template<class FormatContext>
auto format(const T& value, FormatContext& ctx) const;

std::formatter<T, charT> from <format> is the customization point used by std::format and related functions for one argument. A formatter meets the BasicFormatter/Formatter requirements: parse(ctx) analyzes the part after the colon and returns the first unconsumed character, normally }, while format(value, ctx) writes through ctx.out() and returns the iterator past its output.

The example specializes std::formatter<Point> for a program-defined type. parse returns ctx.begin(), so only an empty specification is accepted, and format delegates coordinate output to std::format_to; the result is p=(3, 4). The specialization must be visible when the format literal is checked. Options read by parse can be stored in the formatter object and used later by format.

Leaving an unmatched part of the specification, other than stopping at }, requires std::format_error. The format signature should work with the required value qualification and a const formatter so that const values are formattable under the C++23 requirements; its returned iterator must be the actual end of output. A formatter may be specialized for a program-defined type, but standard-type specializations cannot be arbitrarily replaced. Context and iterator lifetimes do not extend beyond the call.

Examples

#include <format>
#include <iostream>

struct Point {
    int x;
    int y;
};

template<>
struct std::formatter<Point> {
    constexpr auto parse(std::format_parse_context& ctx) {
        return ctx.begin();
    }

    auto format(const Point& point, std::format_context& ctx) const {
        return std::format_to(ctx.out(), "({}, {})", point.x, point.y);
    }
};

int main() {
    std::cout << std::format("p={}", Point{3, 4}) << '\n';
}

Result

p=(3, 4)

std::formatter → p=(3, 4)

Sources