1. 传统格式化方式的痛点
在 C++17 以前,字符串格式化主要依赖于 printf 系列函数、std::ostringstream、以及第三方库如 fmt。
printf语法不安全,类型不匹配会导致未定义行为。ostringstream语法冗长,性能不如printf。- 第三方库需要额外依赖,且 API 与 C++ 标准库不一致。
2. C++20 引入 std::format
C++20 在 `
` 头文件中提供了 `std::format`,其设计灵感来自 Google 的 `fmt` 库,兼具安全性、可读性与高性能。 ### 2.1 语法与使用 “`cpp #include #include int main() { std::string name = “Alice”; int age = 30; double salary = 12345.678; std::string msg = std::format( “姓名:{},年龄:{: buf(1024); std::format_to(std::back_inserter(buf), “点数: {}”, 42); std::string result(buf.begin(), buf.end()); “` ## 3. 与 `std::printf` 的对比 | 特性 | `std::printf` | `std::format` | |——|—————|—————| | 类型安全 | 否 | 是 | | 编译期检查 | 否 | 是 | | 对齐/宽度 | `%5d` | `{:n}` | 右对齐 | `”{:>5}”.format(42)` → `” 42″` | | `{:^n}` | 居中 | `”{:^5}”.format(42)` → `” 42 “` | | `{:x}` | 十六进制 | `”{:x}”.format(255)` → `”ff”` | | `{:03d}` | 前导 0,宽度 3 | `”{:03d}”.format(7)` → `”007″` | | `{:f}` | 浮点 | `”{:.2f}”.format(3.1415)` → `”3.14″` | ## 5. 如何在项目中使用 `std::format` 1. **编译器支持** – GCC ≥ 11、Clang ≥ 13、MSVC ≥ 19.28 支持 ` `。 – 若使用较旧编译器,可回退到 `fmt` 库。 2. **链接** – 标准库已包含实现,无需额外链接。 – 若编译器未完整实现,可能需要 `-lstdc++fs` 或类似标志。 3. **示例** “`cpp #include #include #include void log_error(const std::string& file, int line, const std::string& msg) { std::string out = std::format(“[{}:{}] ERROR: {}\n”, file, line, msg); std::ofstream log(“app.log”, std::ios::app); log