std::format是C++20引入的类型安全、语法简洁的现代化字符串格式化工具,替代sprintf等旧方式,支持占位符、格式说明符及自定义类型特化,但编译器支持有限且运行时解析有性能开销。
std::format 是 C++20 引入的现代化字符串格式化工具,替代了传统的 sprintf、std::ostringstream 等易出错、低效或冗长的方式。它语法简洁、类型安全、支持本地化,并与 Python 的 str.format() 和 Rust 的 format! 风格相似。
直接传入格式字符串和参数,返回 std::string:
std::format("Hello, {}!", "World") → "Hello, World!"
std::format("Pi ≈ {:.2f}", 3.14159) → "Pi ≈ 3.14"
std::format("Value: {:d}", 42) → "Value: 42"(:d 显式指定十进制)占位符为 {},可带索引({0}, {1})或命名(C++23 支持,C++20 暂不支持命名参数)。格式说明符写在冒号后,如 {:.3f}、{:8s}:
{:x}:十六进制(小写),std::format("{:x}", 255) → "ff"
{:#x}:带前缀,→ "0xff"
{:05d}:宽度为 5,左补零,→ "00042"
{:>10}:右对齐,总宽 10,→ " hello"
{:^8}:居中,→ " central "
需为类型特化 std::formatter 模板。例如格式化一个 Poi 结构体:
nt
struct Point { int x, y; };
template<> struct std::formatter : std::formatter {
auto format(Point p, format_context& ctx) const {
return fmt::format_to(ctx.out(), "({},{})", p.x, p.y);
}
};
⚠️ 注意:标准库目前(GCC 13/Clang 16+)对 std::formatter 特化的支持仍在完善中;实践中更推荐使用 fmt 库(std::format 的参考实现),它稳定、高效且兼容性更好。启用 C++20 后,#include 即可使用,但需确认编译器支持(GCC ≥ 13,Clang ≥ 15,MSVC ≥ 19.30)。
std::format 默认进行运行时解析格式串,有一定开销;C++23 引入 std::make_format_args 和编译期检查(如 std::format_string 概念)来优化。当前建议:
std::format
fmt::compile)或手动拼接std::locale 相关功能尚未完全集成),数字分组、货币符号等需自行处理