带有{fmt}的自定义格式说明符,用于自定义类

编程入门 行业动态 更新时间:2024-10-28 16:26:48
本文介绍了带有{fmt}的自定义格式说明符,用于自定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

格式化自己的自定义类型时,如何允许自定义填充等?

How would I go about allowing for custom padding, etc.. when formatting my own custom types?

struct S { int x; }; template<> struct fmt::formatter<S> { template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(const S& s, FormatContext& ctx) { return format_to(ctx.out(), "{}", s.x); } }; S s; s.x = 1; fmt::format("{:<10}", s); // error

推荐答案

由于您似乎只重用了现有的格式说明符,因此可以将操作转发到 formatter< int> :

Since you seem to only reuse existing format specifiers, you can just forward operations to formatter<int>:

template<> struct fmt::formatter<S> { formatter<int> int_formatter; template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { return int_formatter.parse(ctx); } template <typename FormatContext> auto format(const S& s, FormatContext& ctx) { return int_formatter.format(s.x, ctx); } };

如果要使用其他语法,或者不想依赖 formatter< int> ,则还可以手动解析 formatter :: parse .

template<> struct fmt::formatter<S> { enum { left, right } align = right; int width = 0; template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { auto it = ctx.begin(); // parse /align/ if (*it == '<') { align = left; ++it; } // parse /width/ const char* width_str_begin = std::to_address(it); const char* width_str_bound = std::to_address(ctx.end()); auto [ptr, ec] = std::from_chars(width_str_begin, width_str_bound, width); auto length = ptr - width_str_begin; it += length; // error handling omitted return it; } template <typename FormatContext> auto format(const S& s, FormatContext& ctx) { return format_to(ctx.out(), align == left ? "{:<{}}" : "{:>{}}", s.x, width); } };

更多推荐

带有{fmt}的自定义格式说明符,用于自定义类

本文发布于:2023-10-15 01:33:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492847.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   说明符   格式   fmt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!