Search code examples
c++functionoperator-keywordostreammanipulators

Calling a function which manipulates the ostream doesn't require parentheses. C++


I know a function cannot be called without a parentheses, however, let's say I have this piece of source code:

#include<iostream>
using namespace std;

ostream& test(ostream& os){
os.setf(ios_base::floatfield);
return os;
}

int main(){
cout<<endl<<scientific<<111.123456789;
cout<<endl<<test<<111.123456789;
}

   /// Output:
   /// 1.11235e+002
   /// 111.123

There isn't any overloading for the left-shift operator, yet when I call the test(ostream& os) function in the cout at the main function, it does not require any parentheses. My question is why?


Solution

  • There isn't any overloading for the left-shift operator

    Yes there is, it's defined in <ostream>.

    It uses exactly the same technique that allows endl and scientific to work. There is an overload taking a function pointer, which calls the function pointer when it's written to a stream.

    basic_ostream has these member functions which accept function pointers:

    // 27.7.3.6 Formatted output:
    basic_ostream<charT,traits>&
    operator<<(basic_ostream<charT,traits>& (*pf)(basic_ostream<charT,traits>&))
    { return pf(*this); }
    
    basic_ostream<charT,traits>&
    operator<<(basic_ios<charT,traits>& (*pf)(basic_ios<charT,traits>&))
    { return pf(*this); }
    
    basic_ostream<charT,traits>&
    operator<<(ios_base& (*pf)(ios_base&))
    { return pf(*this); }
    

    cout << test uses the first of those overloads, which is equivalent to cout.operator<<(&test), which does return test(*this); so the call happens inside the overloaded operator<<.