命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | 工具库‎ | 格式化
 
 
 
 
定义于头文件 <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++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
P2508R1 C++20 该功能没有用户可见的名称 公开了名称 basic_format_string