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 模板。例如格式化一个 Point 结构体:
立即学习“C++免费学习笔记(深入)”;
struct Point { int x, y; };
template<> struct std::formatter<Point> : std::formatter<std::string> {
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 <format></format> 即可使用,但需确认编译器支持(GCC ≥ 13,Clang ≥ 15,MSVC ≥ 19.30)。
std::format 默认进行运行时解析格式串,有一定开销;C++23 引入 std::make_format_args 和编译期检查(如 std::format_string 概念)来优化。当前建议:
std::format
fmt::compile)或手动拼接std::locale 相关功能尚未完全集成),数字分组、货币符号等需自行处理以上就是c++++20格式化库怎么用 c++ std::format用法【新特性】的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号