C++20 std::format: 类型安全的格式化输出
请说明C++20 std::format的设计理念(类似Python的str.format)、基本语法(占位符{}、格式说明符{:spec})、优势(类型安全、可扩展性),以及与printf和iostream的对比。
回答
我还是少年
std::format(C++20,头文件<format>):类型安全的字符串格式化,类似Python的f-string。
基本语法:
std::string msg = std::format("Hello, {}! You are {} years old.", name, age);
{}按顺序替换参数。{0} {1}按索引引用。{:.2f}格式说明符(精度2的小数)。{:>10}左填充、{:<10}右填充、{:^10}居中。{:04x}十六进制4位零填充。
格式说明符:{[index][:fill align sign # 0 width.precision type]}
与printf对比: | 特性 | printf | std::format | |------|--------|------------| | 类型安全 | 否(va_args) | 是(编译期检查) | | 可扩展 | 否 | 支持自定义类型特化std::formatter | | 性能 | 快 | 接近或更好 | | 缓冲区 | 易溢出 | 自动管理string |
与iostream对比:
- 更简洁:
std::cout << std::format("{}", x)vsstd::cout << x。 - 更适合构造字符串(返回std::string)。
- iostream的operator<<不可组合字符串,format可直接生成格式化文本。
自定义类型格式化:特化std::formatter<T>即可。