std::format自C++20起提供类型安全、高效、可扩展的格式化能力,需通过特化std::formatter为自定义类型添加支持,实现parse()解析格式说明符和format()执行格式化,并复用std::format_to递归处理字段,注意constexpr约束、命名空间要求及避免无限递归。

std::format 自 C++20 起正式引入,是类型安全、高效且可扩展的格式化工具。它本身不直接支持用户自定义类型“开箱即用”的格式化,但通过特化 std::formatter 模板,你可以为任意类型(包括自定义类/结构体)添加完整的格式化支持,包括对齐、宽度、精度、填充符,甚至自定义格式说明符(如 {:x}、{:upper} 等)。
为自定义类型特化 std::formatter
核心是为你的类型 T 显式特化 std::formatter<t chart></t>(通常 CharT 是 char)。这个特化必须提供:
-
parse():解析格式字符串(如"<span style="color:#d73a49">^</span>10s"中的^、10、s),存入成员变量供format()使用 -
format():执行实际格式化,调用ctx.out()输出字符,并可递归使用std::format_to格式化子字段
例如,为一个简单坐标结构体添加支持:
struct Point { int x, y; };template
struct std::formatter
char presentation = 'd'; // 默认格式:'d' 表示十进制,可扩展为 'x' 等
constexpr auto parse(format_parse_context& ctx) -> format_parse_context::iterator {
auto it = ctx.begin();
if (it != ctx.end() && *it == 'x') { presentation = 'x'; ++it; }
return it;
}
template
auto format(const Point& p, FormatContext& ctx) const -> typename FormatContext::iterator {
if (presentation == 'x') {
return format_to(ctx.out(), "({:x},{:x})", p.x, p.y);
} else {
return format_to(ctx.out(), "({},{})", p.x, p.y);
}
}
};
之后即可直接使用:std::format("p={:x}", Point{255, 10}) → "p=(ff,a)"。
立即学习“C++免费学习笔记(深入)”;
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
还木有评论哦,快来抢沙发吧~