However, how can a function be stripped of parentheses?
A function name not followed by () is just a reference to that function. This is exactly the same as with any other type:
void foo(int) {} char x = 'a'; char *p = &x; int main() { p;
std::endl is a function (actually a function template) that takes a single parameter of type "stream" and works by inserting an EOL representation into this stream and then flushing it. You can use it like any other function if you want:
std::endl(std::cout);
The last part of the puzzle is that the standard library provides an overload (again, a pattern) of operator << , so the LHS argument is a stream, and the RHS argument is a function; the implementation of this operator calls the RHS argument (function) and passes it to the LHS (stream). Understandably, something like this:
Stream& operator<< (Stream &s, const Function &f) { f(s); return s; }
Therefore, calling std::cout << std::endl causes this operator overload, which in turn calls std::endl(std::cout) , which inserts EOL + flushing.
As for the preferred form (direct call against the << operator), this is definitely the use of << . This is idiomatic, and it makes it easy to compose multiple stream manipulators within a single expression. Like this:
std::cout << "Temperature: " << std::fixed << std::setprecision(3) << temperature << " (rounds to " << std::setprecision(1) << temperature << ')' << std::endl;
Angew
source share