将 std::endl 传递给 std::operator <<

pass std::endl to std::operator <<

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

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

但是当我编译上面这行代码的时候,编译不通过!然后在尝试其他方法后我发现它不编译的原因是因为 std::endl,如果我用 "\n" 替换 std::endl 然后它工作。但是为什么不能把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 给出了更长的错误消息。

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

operator << must take exactly one argument

Does std::cout have a return value?

因为那里的答案有点不对。 std::endl is a manipulator function, there is no overload for them in definitions of standalone operator<< of ostream. It is a member function of 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.

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