【问题标题】:fmtlib: shortcut for user-defined types with no parsing options?fmtlib:没有解析选项的用户定义类型的快捷方式?
【发布时间】:2021-01-21 04:50:28
【问题描述】:

我正在使用{fmt} C++ 库。我为我自己的类型编写了许多fmt::formatter 特化。其中大部分没有格式化选项,因此每个类都有一个 parse(format_parse_context) 的样板实现:

constexpr auto parse(format_parse_context& ctx)
{
    auto it = ctx.begin(), end = ctx.end();
    if (it != end && *it != '}')
        throw format_error("invalid format");
    return it;
}

我希望fmt::formatter 有一个parse 的默认实现,它不需要任何选项,但它没有。这有什么捷径吗?类似于fmt::optionless_formatter 类的东西?

【问题讨论】:

    标签: c++ fmt


    【解决方案1】:

    parse 的实现可以简单得多:

    constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }
    

    您还可以通过继承或组合重用现有的 formatter 特化。

    【讨论】:

    • 我同意这将接受空格式规范,但它也会愉快地使用任意文本并且什么都不做。在这种情况下,我宁愿报告错误。
    • 它会给你一个错误,你不必自己做检查:godbolt.org/z/rd6saj
    • 优秀。我猜fmltlib 对parse() 的返回值做了一些错误检查。谢谢!
    猜你喜欢
    • 2023-03-02
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    相关资源
    最近更新 更多