【问题标题】:pass std::endl to std::operator <<将 std::endl 传递给 std::operator <<
【发布时间】:2015-09-17 22:58:54
【问题描述】:

在这个Stack Overflow answer 它说std::cout &lt;&lt; "Hello World!" &lt;&lt; std::endl; 与

相同
std::operator<<(std::operator<<(std::cout, "Hello World!"), std::endl);

但是当我编译上面的行代码时,它没有编译!然后在尝试了其他方法后,我发现它无法编译的原因是因为std::endl,如果我将std::endl 替换为"\n",那么它就可以工作。但是为什么不能将std::endl 传递给std::operator&lt;&lt;?

或者更简单地说,std::cout&lt;&lt;std::endl; 和 std::operator&lt;&lt;(std::cout, std::endl); 不一样吗?

编辑

使用icpc test.cpp编译时,报错信息为 error: no instance of overloaded function "std::operator&lt;&lt;" matches the argument list argument types are: (std::ostream, &lt;unknown-type&gt;) std::operator&lt;&lt;(std::cout, std::endl);

而g++ test.cpp 给出的错误信息要长得多。

【问题讨论】:

  • 后一个问题可以通过尝试那行代码来回答。和“......它不编译!”意义不大,除非您还包含 错误消息,当它编译失败时在您的问题中。
  • 我试过了,std::operator&lt;&lt;(std::cout, std::endl); 无法编译。
  • 操纵器的重载是成员函数,所以std::cout.operator&lt;&lt;(std::endl)
  • std::operator &lt;&lt;和std::cout.operator &lt;&lt;有什么区别?您认为我在哪里可以找到对std::operator &lt;&lt; 的引用?
  • @Allanqunzi 是成员函数调用 vs 非成员函数调用。类似于 print(x, "hi") 与 x.print("hi")。 Though operator functions are found differently 比其他名字。

标签: c++ std


【解决方案1】:

这是因为那里的答案有点错误。 std::endl 是一个操纵器函数,在 ostream 的独立 operator&lt;&lt; 的定义中它们没有重载。它是basic_ostream 的成员函数。

换句话说,呈现的调用是错误的。它应该是以下之一:

#include <iostream>
int main() {
    std::endl(std::operator<<(std::cout, "Hello World!"));
    std::operator<<(std::cout, "Hello World!").operator<<(std::endl);

    //of course if you pass new line as a supported type it works
    std::operator<<(std::operator<<(std::cout, "Hello World!"), '\n');
    std::operator<<(std::operator<<(std::cout, "Hello World!"), "\n");
    std::operator<<(std::operator<<(std::cout, "Hello World!"), string("\n"));
    return 0;
}

Live examples.

好吧,确实有人说流库没有标准中最漂亮的设计。

【讨论】:

  • 令我惊讶的是,第一个电话就奏效了。这是在哪里定义的?作为 std::namespace 中的全局运算符?甚至更好:operator&lt;&lt;(std::cout, "hello, world").operator&lt;&lt;(std::endl) 以便 ADL 找到 std::operator,对吗?
  • @5gon12eder 是的,我包含了工作示例作为编辑。
  • @5gon12eder 哦,当然。这是一种习惯,using 来自 ideone 标准模板的 copy-pasta。
  • 感谢您的解释。还有一个问题,ostream和std::operator &lt;&lt;中的operator &lt;&lt;有什么区别,在我问的问题中是std::operator &lt;&lt;,但在你的解释中是ostream::operator &lt;&lt;。
  • @WorldSEnder 我不确定你在问什么。但我编辑答案以提供链接。 operator&lt;&lt;(std::basic_ostream) 在 ostream 中定义,ADL 在链接的问题和答案中有很好的描述。
【解决方案2】:

我不知道这个话题,但我认为这两个问题和答案与您的问题有些相关,可能会帮助您找到解决方案

operator << must take exactly one argument

Does std::cout have a return value?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    相关资源
    最近更新 更多