【问题标题】:C++ fmt library, formatting a single argument with just format specifierC++ fmt 库,仅使用格式说明符格式化单个参数
【发布时间】:2019-10-29 00:40:42
【问题描述】:

使用 C++ fmt 库,并给定一个裸格式说明符,有没有办法使用它来格式化单个参数?

// example
std::string str = magic_format(".2f", 1.23);

// current method
template <typename T>
std::string magic_format(const std::string spec, const T arg) {
    return fmt::format(fmt::format("{{:{}}}", spec), arg);
}

虽然上述实现符合我的要求,但我更喜欢一种不需要我在此过程中构建新的临时字符串的方式。

【问题讨论】:

    标签: c++ formatting fmt


    【解决方案1】:

    您可以直接使用formatter&lt;T&gt; 来做到这一点:

    
    template <typename T>
    std::string magic_format(fmt::string_view spec, const T& arg) {
      fmt::formatter<T> f;
      fmt::format_parse_context parse_ctx(spec);
      f.parse(parse_ctx);
      std::string str;
      auto out = std::back_inserter(str);
      using context = fmt::format_context_t<decltype(out), char>;
      auto args = fmt::make_format_args<context>(arg);
      context format_ctx(out, args, {});
      f.format(arg, format_ctx);
      return str;
    }
    

    天箭:https://godbolt.org/z/Ras_QI

    【讨论】:

      猜你喜欢
      • 2016-05-29
      • 1970-01-01
      • 2017-08-04
      • 2018-07-01
      • 2022-01-04
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多