
要使用C++20的 std::format 库进行类型安全的格式化输出,需要确保编译器支持 C++20 并正确启用相关功能。与传统的 printf 或 stringstream 相比,std::format 提供了更安全、更简洁、更高效的格式化方式,避免了格式字符串与参数不匹配导致的运行时错误。
启用 C++20 和包含头文件
使用 std::format 前,必须包含
示例代码:
#include#include iostream>
int main() {
std::string message = std::format("Hello, {}! You have {} new messages.", "Alice", 5);
std::cout return 0;
}
编译命令(以 g++ 为例):
立即学习“C++免费学习笔记(深入)”;
g++ -std=c++20 -o format_example format.cpp注意:截至当前,GCC 需要版本 13 及以上才完整支持
基本用法与占位符
std::format 使用类似 Python 的格式语法,通过花括号 {} 表示占位符,自动推导参数类型,杜绝类型不匹配问题。
- 按顺序填充:{} 按参数顺序依次替换
- 指定索引:{0}, {1} 可重复或乱序引用参数
- 命名参数暂未在标准中支持,但可通过结构体配合自定义 formatter 实现
示例:
std::format("The value of {} is {}", "x", 42);std::format("Reorder: {1}, {0}", "first", "second"); // 输出:Reorder: second, first
格式说明符
在 {} 中使用冒号后接格式说明符,可控制输出格式,如对齐、填充、精度、进制等。
- {:>10} —— 右对齐,宽度10
- {:+} —— 显示正负号
- {:.2f} —— 浮点数保留两位小数
- {:x} —— 十六进制输出
- {:#x} —— 带 0x 前缀的十六进制
示例:
std::format("{:>8}", 255); // " 255"std::format("{:06.2f}", 3.14159); // "003.14"
std::format("{:#x}", 255); // "0xff"
支持自定义类型的格式化
对于自定义类型,需特化 std::formatter 模板,使其兼容 std::format。
示例:为一个简单的 Point 结构体添加格式化支持
#includestruct Point {
double x, y;
};
template
struct std::formatter
constexpr auto parse(auto& ctx) { return ctx.begin(); }
auto format(const Point& p, auto& ctx) const {
return std::format_to(ctx.out(), "({:.1f}, {:.1f})", p.x, p.y);
}
};
// 使用:
std::format("Position: {}", Point{1.23, 4.56}); // 输出:Position: (1.2, 4.6)
关键是实现 parse 和 format 成员函数,parse 通常用于解析格式字符串中的选项,format 使用 std::format_to 将内容写入输出迭代器。
基本上就这些。std::format 是现代 C++ 推荐的格式化方法,类型安全且表达力强。只要环境支持,应优先于 sprintf、printf 等传统方式。










