Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FMT C++ library: allow user to set format specifiers for custom type

Tags:

c++

fmt

I have a custom type, for example

struct custom_type
{
    double value;
};

I want to set a custom FMT formatter for this type. I do the following and it works:

namespace fmt
{
    template <>
    struct formatter<custom_type> {
        template <typename ParseContext>
        constexpr auto parse(ParseContext &ctx) {
        return ctx.begin();
    };

    template <typename FormatContext>
    auto format(const custom_type &v, FormatContext &ctx) {
        return format_to(ctx.begin(), "{}", v.value);
    }
};

But the problem is, that output format is set by template code, with this "{}" expression. And I want to give a user opportunity to define the format string himself.

For example:

custom_type v = 10.0;
std::cout << fmt::format("{}", v) << std::endl;    // 10
std::cout << fmt::format("{:+f}", v) << std::endl; // 10.000000

How can I do this?

Currently, when I set the custom format string, I get

 what():  unknown format specifier
like image 955
Lecko Avatar asked May 20 '19 11:05

Lecko


1 Answers

The easiest solution is to inherit formatter<custom_type> from formatter<double>:

template <> struct fmt::formatter<custom_type> : formatter<double> {
  auto format(custom_type c, format_context& ctx) {
    return formatter<double>::format(c.value, ctx);
  }
};

https://godbolt.org/z/6AHCOJ

like image 51
vitaut Avatar answered Sep 30 '22 02:09

vitaut