在此Stack Overflow answer
它说std::cout << "Hello World!" << std::endl;
与
std::operator<<(std::operator<<(std::cout, "Hello World!"), std::endl);
但是当我编译上面的代码时,它没有编译!然后在尝试了其他事情之后我发现它没有编译的原因是因为std::endl
,如果我用std::endl
替换"\n"
那么它就可以了。但是为什么你无法将std::endl
传递给std::operator<<
?
或者更简单地说,std::cout<<std::endl;
与std::operator<<(std::cout, std::endl);
相同?
修改
使用icpc test.cpp
进行编译时,错误消息为
error: no instance of overloaded function "std::operator<<" matches the argument list argument types are: (std::ostream, <unknown-type>) std::operator<<(std::cout, std::endl);
和g++ test.cpp
会提供更长的错误消息。
答案 0 :(得分:5)
这是因为答案有点不对劲。 std::endl
是一个操纵函数,在ostream
的独立operator<<
的定义中没有重载。它是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;
}
嗯,有些人确实说流库没有标准中最漂亮的设计。
答案 1 :(得分:1)
我不知道这个主题,但我认为这两个问题和答案与您的问题有些相关,可能会帮助您找到解决方案