User-defined Types

Learn how to format user-defined types apart from basic types and strings.

We'll cover the following

To format a user-defined type, I have to specialize the class std::formatter for my user-defined type. This means, in particular, I have to implement the member functions parse and format.

  • parse:

    • Accepts the parse context
    • Parses the parse context
    • Returns an iterator to the end of the format specification
    • Throws a std::format_error in case of an error
  • format:

    • Gets the value t, which should be formatted, and the format context fc
    • Formats t according to the format context
    • Writes the output to fc.out()
    • Returns an iterator that represents the end of the output

Let me put the theory into practice and format a std::vector.

Formatting a std::vector

My first specialization of the class std::formatter is as easy as possible. I specify a format specification used for each element of the container.

Get hands-on with 1400+ tech skills courses.