【问题标题】:Adding Arbitrary Texts to fmt's User-defined Type Formatter将任意文本添加到 fmt 的用户定义类型格式化程序
【发布时间】:2020-08-25 13:14:26
【问题描述】:

我想知道向fmt::formatter::format 添加一些任意文本的正确方法是什么。基本上,我想为我的对象命名。当前的实现有效,但我不确定它是否可以做得更好,而且我觉得我的垂直对齐技巧可以做得更好。

namespace fmt {
  template <>
  struct formatter<Experiment> {
    
    constexpr auto parse(format_parse_context& ctx) {
      return ctx.begin();
    }
    
    template <typename FormatContext>
    auto format(const Experiment& e, FormatContext& ctx) {
      ctx.out() = format_to(ctx.out(), "Experiment:\n\t\t\t\t");
      return format_to(ctx.out(),
                       "{}", join(e.begin(), e.end(), "\n\t\t\t\t"));
    }
  };
}

【问题讨论】:

    标签: c++ c++20 fmt


    【解决方案1】:

    您可以通过ctx.out()返回的输出迭代器复制文本:

        template <typename FormatContext>
        auto format(const Experiment& e, FormatContext& ctx) {
          auto out = ctx.out();
          auto text = std::string_view("Experiment:\n\t\t\t\t");
          out = std::copy_n(text.data(), text.size(), out);
          return format_to(out, "{}", join(e.begin(), e.end(), "\n\t\t\t\t"));
        }
    

    请注意,分配给ctx.out() 没有多大意义,因为您分配给一个被丢弃的临时对象。相反,您应该从 format 函数返回过去的迭代器。

    关于对齐,如果你知道最大宽度,你可以使用宽度格式说明符进行填充。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-17
      相关资源
      最近更新 更多