format/color.cpp

The following code example is taken from the book
C++23 - The Complete Guide by Nicolai M. Josuttis, Leanpub, 2026
The code is licensed under a Creative Commons Attribution 4.0 International License. Creative Commons License

// raw code

#include <iostream>
#include <string>
#include <format>

enum class Color { red, green, blue };

template<> struct std::formatter<Color> : std::formatter<std::string>
{
  auto format(Color c, auto& ctx) const {
    std::string value;
    switch (c) {
      case Color::red:   value = "red";
                         break;
      case Color::green: value = "green";
                         break;
      case Color::blue:  value = "blue";
                         break;
      default:    value = std::format("Color{}", static_cast<int>(c));
                  break;
    }
    return std::formatter<std::string>::format(value, ctx);
  }
};

int main()
{
  Color col = Color::red;
  std::cout << std::format("col: {:>10}\n", col);
  col = Color::green;
  std::cout << std::format("col: {:>10}\n", col);
  col = Color{13};
  std::cout << std::format("col: {:>10}\n", col);
}