命名空间
变体
操作

std::formatter<pair-or-tuple>

来自 cppreference.cn
< cpp‎ | utility‎ | format
 
 
 
 
定义于头文件 <format>
template< class CharT, std::formattable<CharT>... Ts >
struct formatter</*pair-or-tuple*/<Ts...>, CharT>;
(自 C++23 起)

用于 std::formatter 的模板特化,针对 std::pairstd::tuple,允许用户使用 格式化函数 将 pair 或 tuple 转换为其文本表示形式,作为元素的集合。

仅供演示用的名称 /*pair-or-tuple*/ 表示类模板 std::pairstd::tuple

如果 (std::formattable<const Ts, CharT> && ...)true,则此特化满足 Formatter 的要求。它始终满足 BasicFormatter 的要求。

内容

[编辑] 格式规范

tuple-format-spec 的语法是

tuple-fill-and-align (可选) width (可选) tuple-type (可选)

tuple-fill-and-align 的解释方式与 fill-and-align 相同,除了 tuple-fill-and-align 中的 fill 是除 {}: 之外的任何字符。

width标准格式宽度规范 中描述。

tuple-type 更改了 tuple 的格式化方式,某些选项仅对某些参数类型有效。

可用的 tuple 表示类型有

  • m:表示开始和结束括号都应为 "",而分隔符应为 ": "
  • 如果选择 m 作为 tuple-type,则除非 sizeof...(Ts) == 2true,否则程序是非良构的。
  • n:表示分隔符、开始和结束括号都应为 ""

[编辑] 成员对象

成员名称 定义
underlying_ (私有) 类型为 std::tuple<std::formatter<std::remove_cvref_t<Ts>, CharT>...> 的底层格式化器的 tuple
(仅供演示的成员对象*)
separator_ (私有) 表示 tuple 格式化结果分隔符的字符串 (默认为 ", ")
(仅供演示的成员对象*)
opening-bracket_ (私有) 表示 tuple 格式化结果开始括号的字符串 (默认为 "(")
(仅供演示的成员对象*)
closing-bracket_ (私有) 表示 tuple 格式化结果结束括号的字符串 (默认为 ")")
(仅供演示的成员对象*)

[编辑] 成员函数

set_separator
为 tuple 格式化结果设置指定的分隔符
(公共成员函数)
set_brackets
为 tuple 格式化结果设置指定的开始和结束括号
(公共成员函数)
parse
解析 tuple-format-spec 指定的格式说明符
(公共成员函数)
format
写入 tuple-format-spec 指定的 tuple 格式化输出
(公共成员函数)

std::formatter<pair-or-tuple>::set_separator

constexpr void set_separator( std::basic_string_view<CharT> sep ) noexcept;

sep 赋值给 separator_

std::formatter<pair-or-tuple>::set_brackets

constexpr void set_brackets( std::basic_string_view<CharT> opening,
                             std::basic_string_view<CharT> closing ) noexcept;

分别将 openingclosing 赋值给 opening-bracket_closing-bracket_

std::formatter<pair-or-tuple>::parse

template< class ParseContext >
constexpr auto parse( ParseContext& ctx ) -> ParseContext::iterator;

将格式说明符解析为 tuple-format-spec,并将解析后的说明符存储在当前对象中。

如果存在 tuple-typen 选项,则根据需要修改 opening-bracketclosing-bracketseparator 的值。

对于 underlying_ 中的每个元素 e,调用 e.parse(ctx) 来解析一个空的 format-spec,并且,如果 e.set_debug_format() 是有效表达式,则调用 e.set_debug_format()

返回一个迭代器,该迭代器超过 tuple-format-spec 的末尾。

std::formatter<pair-or-tuple>::format

template< class FormatContext >

FormatContext::iterator

format( /*maybe-const-pair-or-tuple*/<Ts...>& elems, FormatContext& ctx ) const;

/*maybe-const-pair-or-tuple*/ 表示

  • 如果 (std::formattable<const Ts, CharT> && ...)true,则为 const /*pair-or-tuple*/
  • 否则为 /*pair-or-tuple*/

按照 tuple-format-spec 的指定,按顺序将以下内容写入 ctx.out()

  • opening-bracket_,
  • 对于 [0sizeof...(Ts)) 中的每个索引 I
  • 如果 I != 0,则为 separator_
  • 通过 std::get<I>(underlying_) 写入 std::get<I>(elems) 的结果,以及
  • closing-bracket_.

返回一个迭代器,该迭代器超过输出范围的末尾。

[编辑] 缺陷报告

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

DR 应用于 已发布行为 正确行为
LWG 3892 C++23 嵌套 tuple 的格式化不正确 已更正

[编辑] 参见

(C++20)
为给定类型定义格式化规则
(类模板) [编辑]