问题描述
我想知道向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
函数返回最后的迭代器。
至于对齐方式,如果您知道最大宽度,则可以使用宽度格式说明符进行填充。