std::runtime_format
来自 cppreference.cn
定义于头文件 <format> |
||
/*runtime-format-string*/<char> runtime_format( std::string_view fmt ) noexcept; |
(1) | (since C++26) |
/*runtime-format-string*/<wchar_t> runtime_format( std::wstring_view fmt ) noexcept; |
(2) | (since 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) | |
1) 使用
s
初始化 str
。2) 显式删除复制构造函数。该类型既不可复制也不可移动。
3) 显式删除赋值。
[编辑] 注释
由于 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); // error auto s1 = std::format(std::move(runtime_fmt), 1); // still error auto s2 = std::format(std::runtime_format("{}"), 1); // ok
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__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 += "{} "; // constructs the formatting string 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) |
在构造时执行编译时格式字符串检查的类模板 (类模板) |