std::format
定义于头文件 <format> |
||
template< class... Args > std::string format( std::format_string<Args...> fmt, Args&&... args ); |
(1) | (自 C++20 起) |
template< class... Args > std::wstring format( std::wformat_string<Args...> fmt, Args&&... args ); |
(2) | (自 C++20 起) |
template< class... Args > std::string format( const std::locale& loc, |
(3) | (自 C++20 起) |
template< class... Args > std::wstring format( const std::locale& loc, |
(4) | (自 C++20 起) |
根据格式化字符串 fmt 格式化 args,并将结果作为字符串返回。如果存在 loc,则用于特定于区域设置的格式化。
自 P2216R3 起,std::format
对格式化字符串执行编译时检查(通过辅助类型 std::format_string 或 std::wformat_string)。如果发现对于要格式化的参数类型无效,则会发出编译错误。如果格式化字符串不能是编译时常量,或者需要避免编译时检查,请使用 std::vformat 或在 fmt 上使用 std::runtime_format
(自 C++26 起) 代替。
以下要求适用于 Args
中的每种类型 T
,其中对于重载 (1,3),CharT
是 char;对于重载 (2,4),CharT
是 wchar_t
- std::formatter<T, CharT> 必须满足 BasicFormatter
- std::formatter<T, CharT>::parse() 必须是 constexpr,因为 P2216R3 (std::vformat 没有此要求)
目录 |
[编辑] 参数
fmt | - |
每个替换字段具有以下格式
1) 没有格式规范的替换字段
2) 带有格式规范的替换字段
| ||||||||||||||||||||||||||||||||||||||||||||||
args... | - | 要格式化的参数 | ||||||||||||||||||||||||||||||||||||||||||||||
loc | - | std::locale 用于特定于区域设置的格式化 |
[编辑] 返回值
一个字符串对象,包含格式化后的结果。
[编辑] 异常
在内存分配失败时抛出 std::bad_alloc。 也会传播任何格式化程序抛出的异常。
[编辑] 注解
提供比格式化字符串要求的参数更多的参数不是错误
std::format("{} {}!", "Hello", "world", "something"); // OK, produces "Hello world!"
从 P2216R3 开始,如果格式化字符串不是常量表达式,则会报错。 在这种情况下可以使用 std::vformat。
std::string f(std::string_view runtime_format_string) { // return std::format(runtime_format_string, "foo", "bar"); // error return std::vformat(runtime_format_string, std::make_format_args("foo", "bar")); // OK }
std::runtime_format 可以直接在 std::string f(std::string_view runtime_format_string) { return std::format(std::runtime_format(runtime_format_string), "foo", "bar"); }
|
(自 C++26 起) |
[编辑] 示例
#include <format> #include <iostream> #include <string> #include <string_view> template<typename... Args> std::string dyna_print(std::string_view rt_fmt_str, Args&&... args) { return std::vformat(rt_fmt_str, std::make_format_args(args...)); } int main() { std::cout << std::format("Hello {}!\n", "world"); std::string fmt; for (int i{}; i != 3; ++i) { fmt += "{} "; // constructs the formatting string std::cout << fmt << " : "; std::cout << dyna_print(fmt, "alpha", 'Z', 3.14, "unused"); std::cout << '\n'; } }
输出
Hello world! {} : alpha {} {} : alpha Z {} {} {} : alpha Z 3.14
[编辑] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
P2216R3 | C++20 | 对于无效的格式化字符串,抛出 std::format_error | 无效的格式化字符串导致编译时错误 |
P2418R2 | C++20 | 既不是 const 可用也不是可复制的对象 (例如类似生成器的对象)不可格式化 |
允许格式化这些对象 |
P2508R1 | C++20 | 此工具没有用户可见的名称 | 名称 basic_format_string 被公开 |
[编辑] 参见
(C++20) |
通过输出迭代器写出其参数的格式化表示 (函数模板) |
(C++20) |
通过输出迭代器写出其参数的格式化表示,不超过指定大小 (函数模板) |