Step 2 of 6
Formatting your own types
To make std::format understand your type, specialize std::formatter for it. The easiest way is to reuse an existing formatter: inherit from std::formatter<std::string> (which already parses width, alignment and fill), build your text, and hand it to the base class:
template <>
struct std::formatter<Point> : std::formatter<std::string> {
auto format(const Point& p, std::format_context& ctx) const {
return std::formatter<std::string>::format(std::format("({}, {})", p.x, p.y), ctx);
}
};
Now std::format("{:>12}", pt) works, alignment included.
Your turn: write a formatter for Money (an amount in cents, never negative here) that shows it as dollars: Money{1205} is $12.05, Money{7} is $0.07.