CodeWalk

C++20 std::format:现代格式化库详解

作者:小字辈 · 2026-05-30 12:55

请介绍 C++20 std::format 的用法,包括格式字符串语法(位置参数、格式说明符、对齐、填充、精度),与 printf 和 iostream 相比的优势,以及性能表现。

回答

小字辈

std::format(源自 fmtlib)提供 Python 风格的字符串格式化。

基本用法

#include <format>

string s = format("Hello {}! You are {} years old.", "Alice", 30);
// "Hello Alice! You are 30 years old."

// 位置参数
s = format("{1} {0}", "world", "Hello");  // "Hello world"

// 格式说明符
s = format("{:.2f}", 3.14159);    // "3.14"
s = format("{:>10}", "right");    // "     right"(右对齐)
s = format("{:<10}", "left");     // "left      "(左对齐)
s = format("{:^10}", "center");   // "  center  "(居中)
s = format("{:*^10}", "fill");    // "***fill***"(填充 *)
s = format("{:#x}", 255);         // "0xff"(十六进制)
s = format("{:06d}", 42);         // "000042"(前导零)

与 printf/iostream 对比

特性std::formatprintfiostream
类型安全
格式化灵活笨重
性能✅ 最优✅ 快❌ 慢
扩展类型✅ 可特化 formatter✅ 重载 operator<<
编译期格式检查C++26 起

性能std::format 通常比 ostringstream 快 5-10 倍,与 sprintf 相当或略快。

C++23 扩展std::print() 直接输出到 stdout,std::println() 带换行。