命名空间
变体
操作

std::basic_format_string, std::format_string, std::wformat_string

来自 cppreference.cn
< cpp‎ | utility‎ | format
 
 
 
 
定义于头文件 <format>
template< class CharT, class... Args >
struct basic_format_string;
(1) (自 C++20 起)
template< class... Args >

using format_string =

    basic_format_string<char, std::type_identity_t<Args>...>;
(2) (自 C++20 起)
template< class... Args >

using wformat_string =

    basic_format_string<wchar_t, std::type_identity_t<Args>...>;
(3) (自 C++20 起)

类模板 std::basic_format_string 封装了一个 std::basic_string_view,它将被格式化函数使用。

std::basic_format_string 的构造函数执行编译时格式字符串检查,除非构造函数参数由 std::runtime_format 返回(自 C++26 起)

内容

[编辑] 成员函数

(构造函数)
构造一个 basic_format_string,如果参数不是格式字符串,则引发编译错误
(公共成员函数)
get
返回封装的字符串
(公共成员函数)

std::basic_format_string::basic_format_string

template< class T >
consteval basic_format_string( const T& s );
(1)
basic_format_string( /* runtime-format-string */<CharT> s ) noexcept;
(2) (自 C++26 起)
1) 构造一个 basic_format_string 对象,它存储字符串 s 的视图。如果参数不是编译时常量,或者如果它不能被解析为格式化参数类型 Args 的格式字符串,则构造是非良构的。
此重载仅在 const T& 建模 std::convertible_to<std::basic_string_view<CharT>> 时参与重载解析。
2) 构造一个 basic_format_string 对象,它存储由 std::runtime_format 返回的字符串 s 的视图。它在构造时不会执行格式字符串检查。

参数

s - 一个表示格式字符串的对象。格式字符串由以下部分组成:
  • 普通字符(除了 {}),它们被不变地复制到输出中,
  • 转义序列 {{}},它们在输出中分别被替换为 {},以及
  • 替换字段。

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

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

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

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

(自 C++23 起)
(自 C++26 起)
  • 对于其他可格式化类型,格式规范由用户定义的 formatter 特化确定。

std::basic_format_string::get

constexpr std::basic_string_view<CharT> get() const noexcept;

返回存储的字符串视图。

[编辑] 注解

别名模板 format_stringwformat_string 使用 std::type_identity_t 来抑制模板参数推导。通常,当它们作为函数参数出现时,它们的模板参数是从其他函数参数推导出来的。

template<class... Args>
std::string format(std::format_string<Args...> fmt, Args&&... args);
 
auto s = format("{} {}", 1.0, 2);
// Calls format<double, int>. Args are deduced from 1.0, 2
// Due to the use of type_identity_t in format_string, template argument deduction
// does not consider the type of the format string.

[编辑] 示例

[编辑] 缺陷报告

以下行为变更的缺陷报告被追溯应用于先前发布的 C++ 标准。

DR 应用于 已发布行为 正确行为
P2508R1 C++20 此功能没有用户可见的名称 名称 basic_format_string 被公开