fmtlib: shortcut for user-defined types with no parsing options?

Viewed 349

I am using the {fmt} C++ library. I have written many fmt::formatter specializations for my own types. Most of these take no formatting options, so each class has a boilerplate implementation of parse(format_parse_context):

constexpr auto parse(format_parse_context& ctx)
{
    auto it = ctx.begin(), end = ctx.end();
    if (it != end && *it != '}')
        throw format_error("invalid format");
    return it;
}

I was hoping that fmt::formatter has a default implementation of parse that takes no options, but it does not. Is there any shortcut for this? Something like a fmt::optionless_formatter class?

1 Answers

The implementation of parse can be much simpler:

constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }

You can also reuse existing formatter specializations via inheritance or composition.

Related