Reputation: 3260
In this Stack Overflow answer
it says that std::cout << "Hello World!" << std::endl;
is the same as
std::operator<<(std::operator<<(std::cout, "Hello World!"), std::endl);
But when I compile the above line code, it doesn't compile! Then after trying something else I found that the reason it doesn't compile is because of std::endl
, if I replace std::endl
by "\n"
then it works. But why you can not pass std::endl
to std::operator<<
?
Or more simply, isn't std::cout<<std::endl;
the same as std::operator<<(std::cout, std::endl);
?
EDIT
When compile with icpc test.cpp
, the error message is
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);
and g++ test.cpp
gives much much longer error message.
Upvotes: 3
Views: 327
Reputation: 16070
It's because the answer there is a bit wrong. 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.
In other word, the presented invocation is wrong. It should be one of the following:
#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;
}
Well, some people do say that stream library does not have the prettiest design in the standard.
Upvotes: 5
Reputation: 457
I dont know about this topic, but i think these 2 questions and answers are somewhat related to your question and might help you figure out a solution
operator << must take exactly one argument
Does std::cout have a return value?
Upvotes: 1