std::format 类型安全格式化
什么是 std::format
std::format 是 C++20 引入的类型安全格式化函数,用于替代 printf 和字符串拼接。它结合了 printf 的简洁格式语法和 C++ 的类型安全,格式字符串在编译期检查,类型不匹配会直接编译报错。
#include <format>
std::string s = std::format("Hello, {}! You are {} years old.", "Alice", 25);
// 结果: "Hello, Alice! You are 25 years old."std::format vs printf vs 字符串拼接
| 特性 | std::format | printf | 字符串拼接(+ / <<) |
|---|---|---|---|
| 类型安全 | 编译期检查 | 运行时(不安全) | 编译期(安全) |
| 格式语法 | {} 占位符 | %d %s 等 | 无统一语法 |
| 返回类型 | std::string | int | std::string / ostream& |
| 可扩展性 | 支持自定义 formatter | 不支持 | 重载 operator<< |
| 本地化 | 支持 | 有限 | 不直接支持 |
| 性能 | 好 | 好 | 一般(多次分配) |
| 安全风险 | 无 | 格式字符串攻击 | 无 |
基本示例
#include <iostream>
#include <format>
#include <string>
#include <vector>
#include <cmath>
// ============================
// 示例1:基本用法
// ============================
void basic_demo() {
// 自动位置参数
std::string s1 = std::format("{} + {} = {}", 1, 2, 3);
std::cout << s1 << std::endl; // 1 + 2 = 3
// 不同类型混合
std::string s2 = std::format("名字: {}, 年龄: {}, 身高: {}m",
"Alice", 25, 1.68);
std::cout << s2 << std::endl;
// 大括号转义——用 {{ 和 }} 输出字面的 { 和 }
std::string s3 = std::format("集合 {{{}}} 包含 {} 个元素", "a,b,c", 3);
std::cout << s3 << std::endl; // 集合 {a,b,c} 包含 3 个元素
}
// ============================
// 示例2:位置参数
// ============================
void positional_demo() {
// 指定参数位置(0 开始)
std::string s1 = std::format("{0} is {1}, {0} is not {2}",
"C++", "great", "old");
std::cout << s1 << std::endl; // C++ is great, C++ is not old
// 同一个参数可以多次使用
std::string s2 = std::format("{0}{0}{0}", "ha");
std::cout << s2 << std::endl; // hahaha
// 调换顺序
std::string s3 = std::format("{1}, {0}!", "World", "Hello");
std::cout << s3 << std::endl; // Hello, World!
}
// ============================
// 示例3:对齐和填充
// ============================
void alignment_demo() {
// 左对齐(<),右对齐(>),居中(^)
std::cout << std::format("|{:<10}|", "left") << std::endl; // |left |
std::cout << std::format("|{:>10}|", "right") << std::endl; // | right|
std::cout << std::format("|{:^10}|", "center") << std::endl; // | center |
// 自定义填充字符
std::cout << std::format("|{:*<10}|", "star") << std::endl; // |star******|
std::cout << std::format("|{:->10}|", "dash") << std::endl; // |------dash|
std::cout << std::format("|{:=^10}|", "eq") << std::endl; // |====eq====|
// 数字对齐
std::cout << std::format("|{:6}|", 42) << std::endl; // | 42|
std::cout << std::format("|{:<6}|", 42) << std::endl; // |42 |
}
// ============================
// 示例4:整数格式化
// ============================
void integer_demo() {
int n = 42;
// 不同进制
std::cout << std::format("十进制: {}", n) << std::endl; // 42
std::cout << std::format("十进制: {:d}", n) << std::endl; // 42
std::cout << std::format("二进制: {:b}", n) << std::endl; // 101010
std::cout << std::format("八进制: {:o}", n) << std::endl; // 52
std::cout << std::format("十六进制: {:x}", n) << std::endl; // 2a
std::cout << std::format("十六进制大写: {:X}", n) << std::endl; // 2A
// 带前缀
std::cout << std::format("带前缀: {:#b}", n) << std::endl; // 0b101010
std::cout << std::format("带前缀: {:#o}", n) << std::endl; // 052
std::cout << std::format("带前缀: {:#x}", n) << std::endl; // 0x2a
// 前导零
std::cout << std::format("前导零: {:08d}", n) << std::endl; // 00000042
std::cout << std::format("前导零: {:08x}", n) << std::endl; // 0000002a
// 正号
std::cout << std::format("正号: {:+}", n) << std::endl; // +42
std::cout << std::format("正号: {:+}", -n) << std::endl; // -42
std::cout << std::format("空格: {: }", n) << std::endl; // " 42"
}
// ============================
// 示例5:浮点数格式化
// ============================
void float_demo() {
double pi = 3.141592653589793;
// 默认格式
std::cout << std::format("默认: {}", pi) << std::endl;
// 定点小数
std::cout << std::format("定点: {:.2f}", pi) << std::endl; // 3.14
std::cout << std::format("定点: {:.5f}", pi) << std::endl; // 3.14159
// 科学计数法
std::cout << std::format("科学: {:.3e}", pi) << std::endl; // 3.142e+00
std::cout << std::format("科学大写: {:.3E}", pi) << std::endl; // 3.142E+00
// 通用格式(自动选择定点或科学)
std::cout << std::format("通用: {:.3g}", pi) << std::endl; // 3.14
std::cout << std::format("通用: {:.3g}", 1e10) << std::endl; // 1e+10
// 宽度 + 精度
std::cout << std::format("宽度+精度: {:10.3f}", pi) << std::endl; // " 3.142"
// 十六进制浮点
std::cout << std::format("十六进制: {:a}", 1.0) << std::endl;
}
// ============================
// 示例6:字符串格式化
// ============================
void string_demo() {
// 截断字符串
std::cout << std::format("{:.5}", "Hello, World!") << std::endl; // Hello
// 宽度 + 截断
std::cout << std::format("{:10.5}", "Hello, World!") << std::endl; // "Hello "
// 字符
std::cout << std::format("字符: {:c}", 65) << std::endl; // A
}
// ============================
// 示例7:format_to 和 formatted_size
// ============================
void format_to_demo() {
// format_to:写入迭代器
std::string buffer;
std::format_to(std::back_inserter(buffer), "Hello, {}!", "World");
std::cout << "format_to: " << buffer << std::endl;
// format_to_n:限制写入字符数
char arr[10] = {};
std::format_to_n(arr, sizeof(arr) - 1, "Number: {}", 12345);
std::cout << "format_to_n: " << arr << std::endl;
// formatted_size:预计算结果长度
auto size = std::formatted_size("Hello, {}!", "World");
std::cout << "formatted_size: " << size << std::endl; // 13
}
// ============================
// 示例8:编译期格式字符串检查
// ============================
void compile_check_demo() {
// 以下代码会编译错误(格式字符串和参数不匹配):
// std::format("{} {}", 42); // 参数不够
// std::format("{}", 42, 43); // 参数多了
// std::format("{:d}", "hello"); // 类型不匹配
// 正确的用法
std::string s = std::format("{:d} {:s}", 42, "hello");
std::cout << s << std::endl; // 42 hello
}
// ============================
// 示例9:bool 和指针格式化
// ============================
void bool_pointer_demo() {
// bool 格式化
std::cout << std::format("bool: {}", true) << std::endl; // true
std::cout << std::format("bool 数字: {:d}", true) << std::endl; // 1
// 指针格式化
int x = 42;
std::cout << std::format("指针: {}", static_cast<void*>(&x)) << std::endl;
}
int main() {
std::cout << "=== 基本用法 ===" << std::endl;
basic_demo();
std::cout << "\n=== 位置参数 ===" << std::endl;
positional_demo();
std::cout << "\n=== 对齐填充 ===" << std::endl;
alignment_demo();
std::cout << "\n=== 整数 ===" << std::endl;
integer_demo();
std::cout << "\n=== 浮点数 ===" << std::endl;
float_demo();
std::cout << "\n=== 字符串 ===" << std::endl;
string_demo();
std::cout << "\n=== format_to ===" << std::endl;
format_to_demo();
std::cout << "\n=== bool和指针 ===" << std::endl;
bool_pointer_demo();
return 0;
}格式说明符语法
完整语法:{[arg_id][:format_spec]}
格式说明符的结构:[[fill]align][sign][#][0][width][.precision][L][type]
| 部分 | 说明 | 示例 |
|---|---|---|
| fill | 填充字符(默认空格) | * |
| align | 对齐:< 左 > 右 ^ 居中 | < |
| sign | + 总显示符号,- 只负号, 正数前空格 | + |
# | 显示前缀(0x、0b、0) | #x |
0 | 用零填充 | 08d |
| width | 最小宽度 | 10 |
| precision | 浮点精度或字符串最大宽度 | .3 |
L | 使用本地化格式 | Lf |
| type | 表示类型(d、x、f、e 等) | x |
类型说明符一览
| 说明符 | 含义 | 适用类型 |
|---|---|---|
d | 十进制 | 整数 |
b / B | 二进制 | 整数 |
o | 八进制 | 整数 |
x / X | 十六进制 | 整数 |
c | 字符 | 整数/字符 |
f / F | 定点小数 | 浮点数 |
e / E | 科学计数法 | 浮点数 |
g / G | 通用格式 | 浮点数 |
a / A | 十六进制浮点 | 浮点数 |
s | 字符串 | 字符串/bool |
p | 指针 | void* |
? | 转义字符串(C++23) | 字符串/字符 |
适用场景
- 替代 printf 的类型安全格式化
- 生成格式化的日志消息
- 构建对齐的表格输出
- 数值的进制转换显示
- 浮点数的精度控制
- 国际化和本地化格式化
常见问题
std::format 的格式字符串是编译期检查的吗?
是的。C++20 的 std::format 使用 consteval 构造函数在编译期检查格式字符串。如果占位符数量和参数数量不匹配,或者类型说明符和参数类型不兼容,编译器会报错。
std::format 和 fmt 库什么关系?
std::format 的设计基于开源的 {fmt} 库(fmtlib)。{fmt} 库是 std::format 的参考实现,功能更丰富。很多项目在 C++20 之前就使用 {fmt} 库了。
格式字符串可以是运行时变量吗?
C++20 中不可以——格式字符串必须是编译期常量。C++26 引入了 std::runtime_format() 来支持运行时格式字符串。
std::format 支持容器和范围吗?
C++23 增加了对范围和容器的格式化支持(std::format("{}", vec) 可以直接格式化 vector)。
注意事项
- 格式字符串必须是编译期常量(C++20)
{}中的大括号需要用{{和}}转义- 不能混合使用自动编号(
{})和手动编号({0}) std::format返回std::string,有内存分配开销- 高性能场景可以用
format_to写入预分配的缓冲区
编译器支持情况
| 编译器 | std::format | 最低版本 |
|---|---|---|
| GCC | 支持 | 13.0 |
| Clang | 支持 | 14.0 |
| MSVC | 支持 | 19.29 (VS 2019 16.10) |
总结
std::format 是 C++20 引入的现代格式化方案,结合了 printf 的简洁语法和 C++ 的类型安全。格式字符串在编译期检查,类型不匹配直接编译报错,彻底消除了 printf 的格式字符串攻击风险。它支持位置参数、对齐填充、进制转换、精度控制等丰富的格式选项。format_to 可以将结果写入任意输出迭代器避免额外分配。formatted_size 可以预计算结果长度。C++23 进一步增加了对容器、范围和转义字符串的格式化支持。