std::format supports custom formatters via std::formatter specialization.
1#include <format>23struct Color {4 uint8_t r, g, b;5};67template<>8struct std::formatter<Color> {9 char format_type = 'x'; // Default: hex1011 constexpr auto parse(std::format_parse_context& ctx) {12 auto it = ctx.begin();13 if (it != ctx.end() && *it != '}') {14 format_type = *it++;15 }16 return it;17 }1819 auto format(const Color& c, auto& ctx) const {20 if (format_type == 'r') {21 return std::format_to(ctx.out(), "({},{},{})", c.r, c.g, c.b);22 }23 return std::format_to(ctx.out(), "#{:02x}{:02x}{:02x}", c.r, c.g, c.b);24 }25};2627Color red{255, 0, 0};28std::cout << std::format("{}", red); // #ff000029std::cout << std::format("{:r}", red); // (255,0,0)3031// Compile-time format string checking32std::cout << std::format("{} + {} = {}", 1, 2, 3); // OK33// std::cout << std::format("{:z}", red); // Error: invalid format
Steps: