All Recipes
Home/Formatting/Custom Formatters
📝intermediate

Custom Formatters

Create custom formatters for your types

Example Code

cpp
#include <format>
#include <iostream>
#include <string>
struct Point {
double x, y;
};
// Custom formatter for Point
template<>
struct std::formatter<Point> {
// Parse format spec (optional, for custom specifiers)
constexpr auto parse(format_parse_context& ctx) {
return ctx.begin();
}
// Format the Point
auto format(const Point& p, format_context& ctx) const {
return std::format_to(ctx.out(), "({}, {})", p.x, p.y);
}
};
// More complex formatter with format specs
struct Color {
uint8_t r, g, b;
};
template<>
struct std::formatter<Color> {
bool use_hex = false;
constexpr auto parse(format_parse_context& ctx) {
auto it = ctx.begin();
if (it != ctx.end() && *it == 'x') {
use_hex = true;
++it;
}
return it;
}
auto format(const Color& c, format_context& ctx) const {
if (use_hex) {
return std::format_to(ctx.out(),
"#{:02X}{:02X}{:02X}", c.r, c.g, c.b);
}
return std::format_to(ctx.out(),
"rgb({}, {}, {})", c.r, c.g, c.b);
}
};
int main() {
Point p{3.5, 7.2};
std::cout << std::format("Location: {}", p) << std::endl;
// Output: Location: (3.5, 7.2)
Color red{255, 0, 0};
std::cout << std::format("Color: {}", red) << std::endl;
// Output: Color: rgb(255, 0, 0)
std::cout << std::format("Hex: {:x}", red) << std::endl;
// Output: Hex: #FF0000
return 0;
}

Explanation

Custom formatters allow your types to work with std::format. Implement std::formatter<T> with parse() and format() methods. You can support custom format specifiers.

Key Points

  • 1Specialize std::formatter<YourType>
  • 2parse() handles format specifiers
  • 3format() outputs the formatted result
  • 4Use std::format_to for output