Question Details

No question body available.

Tags

c++ fmt stdoptional

Answers (1)

Accepted Answer Available
Accepted Answer
May 27, 2026 Score: 8 Rep: 66,080 Quality: Expert Completeness: 80%

One very simple way to implement formatting codes (the parse function) is to inherit from a formatter that already has the formatting codes you want to use.

Don't write parse at all. Just use the inherited one.

And when you want to use those codes, forward to the base's format function.

template struct fmt::formatter : fmt::formatter { constexpr auto format (std::optional const& op, auto& ctx) const { if(op) return fmt::formatter::format(op.value(), ctx); return format_to(ctx.out(), "-"); } };

Now, if you want the vector's elements to be hex, you should use "{::x}", because "{:x}" is asking the vector itself to be hex.

fmt::println("{::x}", vec);

See it working in Compiler Explorer


As noted in the comments, it's possible that a formatter already exists for every std::optional, in which case you would want to make your custom formatter more specialized to prevent ODR violations.

template requires std::integral //