Eximius
Eximius

Reputation: 307

C++ manipulators?

How does the c++ standard define the recognition of manipulators or just manipulators in general?

For example:

using namespace std;
ostream& hello_manip(ostream& os){
  os<<"Hello there, fine fellow!"; return os;
}
int main(){
  cout<<hello_manip;
} 

The code cout << hello_manip would seem to be translated into operator<<( cout, hello_manip ) or cout.operator<<(hello_manip), but instead it takes up the form of hello_manip( cout ).

Upvotes: 2

Views: 630

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283634

There's an overload of operator<< that accepts a function pointer and invokes it. No magic involved.

Processing of simple manipulators such as yours is described in section 27.7.3.6.3 of the Standard.

basic_ostream<charT,traits>& operator<<(basic_ostream<charT,traits>& (*pf) basic_ostream<charT,traits>&))

  1. Effects: None. Does not behave as a formatted output function (as described in 27.7.3.6.1).
  2. Returns: pf(*this).

basic_ostream<charT,traits>& operator<<(basic_ios<charT,traits>& (*pf) basic_ios<charT,traits>&))

  1. Effects: Calls pf(*this). This inserter does not behave as a formatted output function (as described in 27.7.3.6.1).
  2. Returns: *this.

basic_ostream<charT,traits>& operator<<(ios_base& (*pf)(ios_base&))

  1. Effects: Calls pf(*this). This inserter does not behave as a formatted output function (as described in 27.7.3.6.1).
  2. Returns: *this.

More complex manipulators (which accept parameters and carry state) are implemented by returning functor objects, which have their own operator<< overloads.

Upvotes: 8

Related Questions