c++++20的std::format库解决了传统字符串格式化的多个痛点,1. 提供类型安全性,避免printf中因类型不匹配导致的运行时错误;2. 增强可读性和简洁性,采用类似python的{}占位符语法,提升代码清晰度;3. 优化性能表现,在多数情况下优于stringstream,并在复杂场景中可媲美甚至超越printf;4. 支持自定义类型的格式化,通过特化std::formatter实现统一接口;5. 提升易用性和标准化,简化对齐、精度控制等复杂格式需求。迁移时需注意编译器和标准库支持情况,学习新的格式字符串语法,处理自定义类型的格式化实现,并考虑异常安全及渐进式替换旧代码。

C++20的
std::format
printf
std::stringstream

应用C++20的
std::format
std::format
str.format

要使用它,你需要包含
<format>
立即学习“C++免费学习笔记(深入)”;
一个简单的例子:

#include <format>
#include <string>
#include <iostream>
int main() {
std::string name = "Alice";
int age = 30;
double height = 1.75;
// 基本占位符 {}
std::string s1 = std::format("Hello, {}! You are {} years old.", name, age);
std::cout << s1 << std::endl; // 输出: Hello, Alice! You are 30 years old.
// 位置参数
std::string s2 = std::format("The second arg is {1}, the first is {0}.", name, age);
std::cout << s2 << std::endl; // 输出: The second arg is 30, the first is Alice.
// 格式化选项 (宽度、精度、填充、对齐等)
std::string s3 = std::format("Height: {:.2f}m", height); // 浮点数保留两位小数
std::cout << s3 << std::endl; // 输出: Height: 1.75m
std::string s4 = std::format("{:^20}", "Centered Text"); // 居中,宽度20
std::cout << s4 << std::endl; // 输出: Centered Text
// 结合到输出流
std::cout << std::format("Current value: {}", 123) << std::endl;
// 格式化到现有字符串 (C++23 std::format_to)
// 假设我们有一个足够大的缓冲区
// char buffer[100];
// auto result = std::format_to(buffer, "Value: {}", 42);
// *result = '\0'; // 终止字符串
// std::cout << buffer << std::endl;
return 0;
}std::format
printf
%s
format
<chrono>
std::format
在我看来,
std::format
首先,也是最关键的,就是类型安全性。想当年,用
printf
%d
%s
std::format
其次,是可读性和简洁性。对比
std::stringstream
stringstream
<<
stringstream
std::format
{}{:.2f}再者,性能也是一个不容忽视的优点。
std::stringstream
std::format
printf
format
printf
stringstream
最后,易用性和可扩展性也值得一提。
std::format
std::formatter
std::format
operator<<
std::format
std::format
printf
stringstream
谈到性能,这总是C++开发者绕不开的话题,尤其是在字符串处理这种高频操作上。
std::format
printf
stringstream
在我个人的经验和一些性能测试结果来看,
std::format
与printf
sprintf
printf
format
std::format
printf
std::format
printf
printf
format
与std::stringstream
std::format
std::stringstream
stringstream
stringstream
std::basic_ostream
std::format
相比之下,
std::format
std::string
stringstream
std::format
std::stringstream
简而言之,
std::format
printf
stringstream
std::format
向
std::format
一个很直接的问题就是编译器和标准库支持。
std::format
<format>
-std=c++20
另一个值得关注的点是格式字符串的语法。
std::format
printf
%
stringstream
{}{0}{:.2f}{:^20}printf
stringstream
format_error
自定义类型的格式化也是一个需要手动处理的地方。如果你想让自己的类或结构体能够被
std::format
std::format("My object: {}", my_custom_object);std::formatter
parse
format
// 示例:为自定义类型 MyPoint 实现 std::formatter
#include <format>
#include <string>
#include <iostream>
struct MyPoint {
int x;
int y;
};
// 为 MyPoint 特化 std::formatter
template <>
struct std::formatter<MyPoint> {
// 解析格式字符串,例如 "{:x,y}"
constexpr auto parse(std::format_parse_context& ctx) {
auto it = ctx.begin();
auto end = ctx.end();
// 这里可以解析自定义格式选项,例如是否包含括号等
// 为了简单起见,我们假设没有额外的格式选项
return it;
}
// 格式化 MyPoint 对象
auto format(const MyPoint& p, std::format_context& ctx) const {
// 使用 std::format_to 将格式化的字符串写入输出迭代器
return std::format_to(ctx.out(), "({}, {})", p.x, p.y);
}
};
int main() {
MyPoint p = {10, 20};
std::string s = std::format("The point is {}", p);
std::cout << s << std::endl; // 输出: The point is (10, 20)
return 0;
}此外,错误处理也需要注意。
std::format
std::format_error
printf
stringstream
最后,渐进式迁移往往是最佳策略。不要试图一次性将所有现有的
printf
stringstream
std::format
std::format
以上就是如何应用C++20的format库 替代传统字符串格式化的新方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号