如何在C++ {fmt}库中向formatter传递包装迭代器实现无临时缓存的repr功能
可以通过迭代器包装的方式实现需求,无需使用std::string作为中间格式化缓存。
你之前编译失败的核心原因是:从原上下文获取的ctx.args()是绑定了原输出迭代器类型的basic_format_args实例,与你新构造的使用repr_iterator作为输出迭代器的上下文类型不兼容,只需要先将参数集转换为适配新上下文的类型即可。
修正后的format函数实现如下:
template<typename FormatContext> auto format(Repr<T> repr, FormatContext& ctx) const { auto base_out = ctx.out(); using ReprIter = repr_iterator<decltype(base_out)>; ReprIter repr_it(base_out); // 定义使用自定义迭代器的新上下文类型 using NewFormatContext = fmt::basic_format_context<ReprIter, typename FormatContext::char_type>; // 将原参数集转换为适配新上下文的类型 fmt::basic_format_args<NewFormatContext> adapted_args = ctx.args(); // 构造新上下文传入父类format方法 NewFormatContext new_ctx(repr_it, adapted_args, ctx.locale()); auto ret = fmt::formatter<T>::format(repr.t, new_ctx); // 返回原迭代器位置适配外层上下文 return *ret.iterator; }
该实现可以完全复用父类formatter<T>已经解析完成的格式化说明符,同时逐字符处理输出转义,全程不会产生临时字符串缓存,性能符合你的设计预期。
你现有的repr_iterator和repr_adapter实现已经满足fmt库对输出迭代器的要求,无需额外修改。测试场景下对Repr<const char*>{"abc\ndef"}使用{:>20}等格式说明符,可正常输出右对齐的转义结果。
内容的提问来源于stack exchange,提问作者Bamberghh
相关产品推荐
相关产品推荐

