它在 C++ 标准中的哪个位置记录了 I/O 用户定义类型?

Where in the C++ Standard does it document I/O of user-defined types?

我在 N4140 中查找类似这样的东西,但找不到:

std::ostream& operator<<(std::ostream& os, const T& obj)
{
  // write obj to stream
  return os;
}

这不应该记录在标准中吗?

这是我能找到的关于此事的所有证据(引用 N4140):

13.5

1 A function declaration having one of the following operator-function-ids as its name declares an operator function. A function template declaration having one of the following operator-function-ids as its name declares an operator function template. A specialization of an operator function template is also an operator function. An operator function is said to implement the operator named in its operator-function-id.

operator-function-id:

  operator operator

operator: one of

 new delete new[] delete[]
 + - * / % ˆ & | ~
 ! = < > += -= *= /= %=
 ˆ= &= |= << >> >>= <<= == !=
 <= >= && || ++ -- , ->* ->
 ( ) [ ]

[ Note: The last two operators are function call (5.2.2) and subscripting (5.2.1). The operators new[], delete[], (), and [] are formed from more than one token. —end note ]

6 An operator function shall either be a non-static member function or be a non-member function that has at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration. ...

13.5.2

1 A binary operator shall be implemented either by a non-static member function (9.3) with one parameter or by a non-member function with two parameters. Thus, for any binary operator @, x@y can be interpreted as either x.operator@(y) or operator@(x,y). If both forms of the operator function have been declared, the rules in 13.3.1.2 determine which, if any, interpretation is used.

标准没有任何地方禁止将 std 中的 classes 指定为运算符函数(或任何函数,就此而言)的参数类型。

请注意 13.5/1 中 table 中存在 <<>>。这意味着对任何两种类型重载 operator << 是合法的,其中至少一种类型符合 13.5/6 中列出的条件。 std::ostreamstd::basic_ostream<char> 的类型定义,它是 class。所以重载 operator<< (std::ostream&, T) 对任何类型都有效 T.

这就是标准的全部内容。重载 << 意味着流插入没有特殊规则——没有 必须 是。这只是运算符重载的正常应用。如果您真的想要,您可以为此目的重载 %

我能想到的标准中涉及 << 流的唯一其他地方是:

  • 27.7.3.9/1,对输出流的右值引用的 operator<< 重载,其效果如下:

    1 Effects: os << x

    因此,如果您为 class 重载 <<,输出流右值的标准库插入器将为您的 class.

    [=69= 调用它]
  • 流迭代器 (24.6)。例如,24.6.2/1 表示:

    1 ostream_iterator writes (using operator<<) successive elements onto the output stream from which it was constructed. ...