Namespaces
Variants

std:: vformat

From cppreference.net
定义于头文件 <format>
(1) (C++20 起)
(2) (C++20 起)
(3) (C++20 起)
(4) (C++20 起)

args 持有的格式化参数按照格式字符串 fmt 进行格式化,并将结果以字符串形式返回。如果存在 loc 参数,则用于区域特定的格式化。

目录

参数

fmt - 表示格式字符串的对象。格式字符串包含:
  • 普通字符(除了 { } ),它们会原样复制到输出中,
  • 转义序列 { { } } ,它们在输出中分别被替换为 { } ,以及
  • 替换字段。

每个替换字段具有以下格式:

{ arg-id (optional) } (1)
{ arg-id (optional) : format-spec } (2)
1) 不带格式说明的替换字段
2) 带格式说明的替换字段
arg-id - 指定 args 中参数的索引,其值将用于格式化;如果省略,则按顺序使用参数。

格式字符串中的 arg-id 必须全部显式指定或全部省略。混合手动和自动索引是错误的。

format-spec - 由对应参数的 std::formatter 特化定义的格式规范。不能以 } 开头。

(since C++23)
(since C++26)
  • 对于其他可格式化类型,格式规范由用户定义的 formatter 特化决定。
args - 要格式化的参数
loc - 用于本地化特定格式化的 std::locale

返回值

一个包含格式化结果的字符串对象。

异常

fmt 不是有效格式字符串时抛出 std::format_error ,内存分配失败时抛出 std::bad_alloc 。同时会传播由格式化器或迭代器操作抛出的任何异常。

示例

#include <format>
#include <iostream>
template<typename... Args>
inline void println(const std::format_string<Args...> fmt, Args&&... args)
{
    std::cout << std::vformat(fmt.get(), std::make_format_args(args...)) << '\n';
}
int main()
{
    println("{}{} {}{}", "Hello", ',', "C++", -1 + 2 * 3 * 4);
}

输出:

Hello, C++23

参见