Question

I was wondering: if for example std::endl is a regular function, then why does it lack the call operator (the operator())?

i know that it is designed to be used with the the insertion (<<) and extraction (>>) operators. I tried to call it like this:

std::endl.();

But of course that didn't work.

Was it helpful?

Solution

std::endl is just an ordinary function (or rather, function template) that you can call. You just have to call it with the correct argument:

std::endl(std::cout);    // OK, equivalent to "std::cout << std::endl;"

That's because the ostream overloads the shift operator for function pointers, in a manner equivalent to the following:

ostream & operator<<(ostream & os, ostream & (*f)(ostream &))
{
    return f(os);
}

(It will actually be a template for basic_ostream to deal with any kind of character traits and allocators.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top