たとえば、カスタムタイプがあります
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
最も簡単な解決策は、以下から継承すること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);
}
};
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加