例如,我有一个自定义类型
struct custom_type
{
double value;
};
Run Code Online (Sandbox Code Playgroud)
我想为此类型设置自定义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);
}
};
Run Code Online (Sandbox Code Playgroud)
但是问题是,输出格式是由带有此"{}"表达式的模板代码设置的。我想给用户一个机会自己定义格式字符串。
例如:
custom_type v = 10.0;
std::cout << fmt::format("{}", v) << std::endl; // 10
std::cout << fmt::format("{:+f}", v) << std::endl; // 10.000000
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
目前,当我设置自定义格式字符串时,
what(): unknown format specifier
Run Code Online (Sandbox Code Playgroud)
最简单的解决方案是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);
}
};
Run Code Online (Sandbox Code Playgroud)