3

我创建了一个 Decimal 类并想使用 fmt 库。我读到为格式化程序定义类型的方法是专门化fmt::formatter。但是,文档中没有关于如何调用现有公共基础设施的信息。字段对齐和整体宽度和填充字符的格式代码,例如:这应该是适用于任何类型的通用代码。
如何在不从头重新实现整个规范的情况下编写格式化程序专业化?

我想首先使我的类型与浮点格式说明符兼容,因此当类型从double十进制更改为时,它将继续工作;但随后添加特定于该类型的附加功能。

template <int S, int F>
struct fmt::formatter<Decimal<S,F>> {

constexpr auto parse(format_parse_context& ctx) {
    [[maybe_unused]] auto it = ctx.begin(), end = ctx.end();
    // dummy stub.  just take the whole thing
    it = std::find(ctx.begin(),end, '}');
    return it;
}

template <typename FormatContext>
auto format(const Dec& x, FormatContext& ctx) {
    constexpr size_t bufsize = 64;
    char buf[bufsize];
    const auto end = x.to_chars (buf, buf+bufsize, false);
    const std::string_view sv { buf, size_t(end-buf) };
    return std::copy(sv.begin(),sv.end(),ctx.out());
}
};
4

1 回答 1

3

{fmt} 还没有提供解析标准格式说明符的工具。它在内部使用fmt::detail::parse_format_specs. 它需要进行一些清理并移至公共 API 以供重用。

于 2020-04-01T22:41:40.827 回答