std:: runtime_format
|
定义于头文件
<format>
|
||
|
/*runtime-format-string*/
<
char
>
runtime_format
(
std::
string_view
fmt
)
noexcept
;
|
(1) | (C++26 起) |
|
/*runtime-format-string*/
<
wchar_t
>
runtime_format
(
std::
wstring_view
fmt
)
noexcept
;
|
(2) | (C++26 起) |
返回一个对象,该对象存储可直接用于面向用户的格式化函数的运行时格式字符串,并能隐式转换为
std::basic_format_string
。
目录 |
参数
| fmt | - | 字符串视图 |
返回值
一个持有仅用于说明的类型之运行时格式字符串的对象:
类模板
runtime-format-string
<CharT>
|
template
<
class
CharT
>
struct /*runtime-format-string*/ ; |
( 仅用于说明* ) | |
成员对象
返回的对象包含一个仅用于说明的非静态数据成员
str
,其类型为
std::basic_string_view<CharT>
。
构造函数与赋值操作
|
/*runtime-format-string*/
(
std::
basic_string_view
<
CharT
>
s
)
noexcept
;
|
(1) | |
|
/*runtime-format-string*/
(
const
/*runtime-format-string*/
&
)
=
delete
;
|
(2) | |
|
/*runtime-format-string*/
&
operator
=
(
const
/*runtime-format-string*/
&
)
=
delete
;
|
(3) | |
s
初始化
str
。
注释
由于
runtime_format
的返回类型既不可复制也不可移动,尝试将
runtime_fmt
作为左值传递会阻止
std::basic_format_string
的构造,从而导致程序格式错误。要通过
runtime_format
构造
std::basic_format_string
,需要将
runtime_format
的返回值作为纯右值直接传递给
std::basic_format_string
,此时复制消除机制将确保执行效率。
auto runtime_fmt = std::runtime_format("{}"); auto s0 = std::format(runtime_fmt, 1); // 错误 auto s1 = std::format(std::move(runtime_fmt), 1); // 仍然错误 auto s2 = std::format(std::runtime_format("{}"), 1); // 正确
| 功能测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_format
|
202311L
|
(C++26) | 运行时格式字符串 |
示例
#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::runtime_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)
|
在构造时执行编译期格式字符串检查的类模板
(类模板) |