Writing Your Own Manipulators Without Parameters

You have already seen some of the built-in output stream manipulators, including flush, hex, and setw. Now you will learn how to write your own custom manipulators that don't use parameters. This task requires neither class derivation nor use of complex macros.

Suppose you have a printer that requires the sequence <ESC> [ to enter boldface mode. You could, of course, insert these characters directly into the stream like this:

cout << "regular " << '\033' << '[' << "boldface" << endl;

A less tedious strategy is to define a manipulator bold that inserts the desired sequence. The output statement now becomes:

cout << "regular " << bold << "boldface" << endl;

All that's necessary to define the bold manipulator is the following function:

ostream& bold( ostream& os ) {

return os << '\033' << '[';

}

The bold function is simply a globally defined function that takes an ostream reference argument and returns the ostream reference. It is not a member function or a friend because it doesn't need access to any private class elements. The bold function connects to the stream because the stream's << operator is overloaded to accept that type of function by a declaration that looks something like this:

ostream& ostream::operator<< ( ostream& (*_f)( ostream& ) ); {

(*_f)( *this );

return *this;

}

Indeed, you could use this C++ feature to extend other overloaded operators.

It is incidental that, in this case, bold inserts characters into the stream. The function could do anything at all, but you must remember that it is called when it is inserted into the stream, not necessarily when the adjacent characters are printed. Thus printing could be delayed because of the stream's buffering.