11

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

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
4

2 回答 2

6

最简单的解决方案是继承formatter<custom_type>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

于 2019-10-25T04:03:42.347 回答
0

最后我做到了。我会把它保存在这里,以防其他人需要它。

    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;
    };
于 2019-05-20T15:02:02.793 回答