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 ,则将其用于区域设置特定的格式化。
格式字符串
fmt
在编译时进行检查
除非它从
std::runtime_format
的结果初始化
(自 C++26 起)
。如果在编译时发现格式字符串对于要格式化的参数类型无效,将产生编译错误。
以下要求适用于
Args
中的每个类型
T
,其中
CharT
对于重载
(1,3)
为
char
,对于重载
(2,4)
为
wchar_t
:
- std:: formatter < T, CharT > 必须满足 BasicFormatter 要求
- std:: formatter < T, CharT > :: parse ( ) 必须为 constexpr 以支持编译期格式字符串检查
目录 |
参数
| fmt | - |
每个替换字段具有以下格式:
1)
不带格式说明的替换字段
2)
带格式说明的替换字段
|
||||||||||||||||||||||||||||||||||||||||||||||
| args... | - | 要格式化的参数 | ||||||||||||||||||||||||||||||||||||||||||||||
| loc | - | 用于本地化特定格式化的 std::locale | ||||||||||||||||||||||||||||||||||||||||||||||
返回值
一个包含格式化结果的字符串对象。
异常
在分配失败时抛出 std::bad_alloc 。同时传播由任何格式化程序抛出的异常。
注释
提供比格式字符串所需更多的参数并不是错误:
std::format("{} {}!", "Hello", "world", "something"); // 正常,生成 "Hello world!"
如果格式字符串不是常量表达式
除非它是从
std::runtime_format
的结果初始化
(C++26 起)
,则会产生错误。
std::vformat
没有此要求。
std::string f1(std::string_view runtime_format_string) { // return std::format(runtime_format_string, "x", 42); // 错误 char v1[] = "x"; int v2 = 42; return std::vformat(runtime_format_string, std::make_format_args(v1, v2)); // 正确 } std::string f2(std::string_view runtime_format_string) { return std::format(std::runtime_format(runtime_format_string), "x", 42); // 正确 (C++26) }
示例
#include <format> #include <iostream> #include <set> #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() { #ifdef __cpp_lib_format_ranges const std::set<std::string_view> continents { "Africa", "America", "Antarctica", "Asia", "Australia", "Europe" }; std::cout << std::format("Hello {}!\n", continents); #else std::cout << std::format("Hello {}!\n", "continents"); #endif std::string fmt; for (int i{}; i != 3; ++i) { fmt += "{} "; // 构造格式化字符串 std::cout << fmt << " : "; std::cout << dyna_print(fmt, "alpha", 'Z', 3.14, "unused"); std::cout << '\n'; } }
可能的输出:
Hello {"Africa", "America", "Antarctica", "Asia", "Australia", "Europe"}!
{} : alpha
{} {} : alpha Z
{} {} {} : alpha Z 3.14
缺陷报告
下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
| 缺陷报告 | 应用于 | 发布时行为 | 正确行为 |
|---|---|---|---|
| P2216R3 | C++20 | 对无效格式字符串抛出 std::format_error | 无效格式字符串导致编译时错误 |
| P2418R2 | C++20 |
既不满足常量使用要求也不可复制的对象
(如生成器类对象)不可格式化 |
允许格式化这些对象 |
| P2508R1 | C++20 | 该设施没有对用户可见的名称 |
公开了
basic_format_string
名称
|
参见
|
(C++20)
|
通过输出迭代器写入其参数的格式化表示
(函数模板) |
|
(C++20)
|
通过输出迭代器写入其参数的格式化表示,且不超过指定大小
(函数模板) |