gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:41:11 25 4
gpt4 key购买 nike

我在 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 指定类作为运算符函数(或任何函数)的参数类型。

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

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

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

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

    1 Effects: os << x

    所以如果你重载<<对于您的类,输出流右值的标准库插入器将为您的类调用它。

  • 流迭代器 (24.6)。例如,24.6.2/1 表示:

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

关于c++ - 它在 C++ 标准中的哪个位置记录了用户定义类型的 I/O?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28366444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com