将任意文本添加到fmt的用户定义类型格式化程序

问题描述

我想知道向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"));
    }
  };
}

解决方法

您可以通过 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 函数返回最后的迭代器。

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...