std::format
来自cppreference.com
| 在标头 <format> 定义
|
||
| template< class... Args > std::string format( /*format_string<Args...>*/ fmt, const Args&... args ); |
(1) | (C++20 起) |
| template< class... Args > std::wstring format( /*wformat_string<Args...>*/ fmt, const 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 ,并返回作为 string 的结果。 loc 若存在,则用于本地环境特定的格式化。
若对 Args 中的任一 Ti , std::formatter<Ti, CharT> 不满足格式化器 (Formatter) 要求则行为未定义,其中 CharT 是对重载 (1,3) 为 char ,对重载 (2,4) 为 wchar_t 。
参数
| fmt | - | Args 的合法格式字符串才合法。格式字符串由以下内容组成:
每个替换域拥有下列格式:
arg-id 指定用于格式化其值的 格式说明由对应参数特化的 std::formatter 定义。
|
| args... | - | 要格式化的参数 |
| loc | - | 用于本地环境特定格式化的 std::locale |
返回值
保有格式化结果的 string 对象。
异常
在分配失败时抛出 std::bad_alloc 。并且会传播任何格式化器所抛的异常。
注解
提供多于格式字符串所要求的参数不是错误:
std::format("{} {}!", "Hello", "world", "something"); // OK :产生 "Hello world!"
自 P2216R3 起,格式字符串不是常量表达式是错误。此情况下可使用 std::vformat 。
std::string f(std::string_view runtime_format_string) { // return std::format(runtime_format_string, "foo", "bar"); // 错误 return std::vformat(runtime_format_string, std::make_format_args("foo", "bar")); // OK }
示例
运行此代码
#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 += "{} "; // 构造格式化字符串 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++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| P2216R3 | C++20 | 对非法格式字符串抛出 std::format_error | 非法格式字符串导致编译时错误 |
参阅
| (C++20) |
通过输出迭代器写其参数的格式化表示 (函数模板) |
| (C++20) |
通过输出迭代器写其参数的格式化表示,不超出指定的大小 (函数模板) |