TITLE: Customizing IO manipulators (part II of III) [ Continued from ~clarke/c++tips/manipulatorI. -adc ] RESPONSE: kanze@us-es.sel.de (James Kanze), 3 Aug 94 How does this work? Look at the expression which uses the manipulator: cout << myManip( i ) ; The compiler converts this to: operator<<( cout , myManip( i ) ) ; myManip returns an SMANIP(int), so "operator>>( ostream& , SMANIP(int) )" is called. This operator does nothing more than call the function passed as parameter to the constructor of SMANIP, in this case, myManipFnc, with the stream and the saved argument as parameters. And bingo, the formatting flags are set. If you provide your own class instead of using SMANIP, the operator>> can do just about anything. This is a particularly powerful mechanism. For example, note that the class returned by the manipulator is a temporary. Since the lifetime of temporaries is now fixed at end of full expression, I was able to write a manipulator which takes a printf type formatting string, sets the ios flags/parameters correspondingly, and restores the previous state at the end of the expression (when the temporary is destructed). If anyone feels like trying this, don't forget that you will want to use the manipulator several times in the same expression, e.g.: cout << fmt( "%5d" ) << i << fmt( "%6.2f" ) << f << endl ; The state restored must be that of the first fmt. And instead of i, there might be a function call which outputs (using fmt) to another stream. (Hint: use iword to keep track of the number of temporaries connected to each stream.)