FMT C++ 库:允许用户为自定义类型设置格式说明符

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

我有一个自定义类型,例如

struct custom_type
{
    double value;
};

我想为此类型设置自定义 FMT 格式化程序。我执行以下操作并且有效:

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);
    }
};

但问题是,输出格式是由模板代码设置的,使用这个 "{}" 表达式。我想让用户有机会自己定义格式字符串。

例如:

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

我该怎么做?

目前,当我设置自定义格式字符串时,我得到

 what():  unknown format specifier

我终于做到了。我会保存在这里,以备不时之需。

    template <>
    struct formatter<custom_type> {
        template <typename ParseContext>
        constexpr auto parse(ParseContext &ctx) {
            auto it = internal::null_terminating_iterator<char>(ctx);
            std::string tmp;
            while(*it && *it != '}') 
            {
                tmp += *it;
                ++it;
            }
            m_format=tmp;
            return internal::pointer_from(it);
        }

        template <typename FormatContext>
        auto format(const custom_type &v, FormatContext &ctx) {
            std::string final_string;
            if(m_format.size()>0)
            {   
                final_string="{:"+m_format+"}";
            }
            else
            {
                final_string="{}";
            }
            return format_to(ctx.begin(), final_string, v.value);
        }
        mutable std::string m_format;
    };

最简单的解决方案是从 formatter<double> 继承 formatter<custom_type>:

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