

新闻资讯
技术学院在C++20之前,字符串格式化主要依赖于C风格的printf或手动拼接,既不安全也不方便。C++20引入了std::format,基于Python的str.format()设计,提供类型安全、可扩展且高性能的格式化方式。
std::format使用类似Python的占位符语法,编译时检查类型,避免缓冲区溢出和类型不匹配问题。
包含头文件:#include
std::string result = std::format("Hello, {}! You are {} years old.", "Alice", 25);
// 输出: Hello, Alice! You are 25 years old.
支持位置参数和命名参数:
参数(如{name}),但提案已在路上在{}中使用:后接格式说明符,控制对齐、精度、进制等。
要让自定义类型支持std::format,需特化std::formatter模板。
struct Point {
int 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(), "({},{})", p.x, p.y);
}
};
std::format("Position: {}", Point{1, 2}); // → Position: (1,2)
关键点:
parse:解析格式字符串(如支持:x或:y可在此处理)format:实际写入格式化内容,使用std::format_to写入输出迭代器std::format比printf稍慢但更安全,比流操作符更简洁高效。
(如libstdc++需定义__cpp_lib_format)std::vformat配合std::make_format_args实现动态格式化基本上就这些。std::format统一了C++的格式化需求,类型安全又易于扩展,是现代C++字符串处理的推荐方式。