std::dynamic_format
来自cppreference.com
| 在标头 <format> 定义
|
||
| |
(1) | (C++26 起) |
| |
(2) | (C++26 起) |
返回一个对象,它存储一个可以直接在面向用户的格式化函数中使用的动态格式字符串,且可以隐式转换为 std::basic_format_string。
参数
| fmt | - | 字符串视图 |
返回值
一个具有以下仅用于阐释的类型的含有动态格式字符串的对象:
类模板 dynamic-format-string <CharT>
| |
(仅用于阐述*) | |
成员对象
所返回的对象包含一个 std::basic_string_view<CharT> 类型的仅用于阐释的非静态数据成员 str。
构造函数与赋值
| |
(1) | |
| |
(2) | |
| |
(3) | |
1) 以
s 初始化 str。2) 复制构造函数被显式弃置。此类型既不可复制也不可移动。
3) 赋值被显式弃置。
注解
由于 dynamic_format 的返回类型既不可复制也不可移动,所以尝试把 dynamic_fmt 作为泛左值进行传递会妨碍 std::basic_format_string 的构造,这导致程序非良构。要从 dynamic_format 构造 std::basic_format_string,dynamic_format 的返回值应直接按纯右值传递给 std::basic_format_string,这样会保证发生复制消除。
auto dynamic_fmt = std::dynamic_format("{}");
auto s0 = std::format(dynamic_fmt, 1); // 错误
auto s1 = std::format(std::move(dynamic_fmt), 1); // 仍然错误
auto s2 = std::format(std::dynamic_format("{}"), 1); // ok
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_format |
202311L |
(C++26) | 运行时格式字符串 |
202603L |
(C++26) | 重命名 runtime_format 为 dynamic_format
|
示例
运行此代码
#include <format>
#include <print>
#include <string>
#include <string_view>
int main()
{
std::print("Hello {}!\n", "world");
std::string fmt;
for (int i{}; i != 3; ++i)
{
fmt += "{} "; // 构造格式化字符串
std::print("{} : ", fmt);
std::println(std::dynamic_format(fmt), "alpha", 'Z', 3.14, "unused");
}
}
输出:
Hello world!
{} : alpha
{} {} : alpha Z
{} {} {} : alpha Z 3.14
参阅
(C++20) |
在新字符串中存储参数的格式化表示 (函数模板) |
(C++20) |
std::format 的使用类型擦除的参数表示的非模板变体 (函数) |
(C++20)(C++20)(C++20) |
在构造时执行编译期格式字符串检查的类模板 (类模板) |