News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

C++ TIps: IO - Customizing IO manipulators (part II of III)

Started by ben2ong2, October 06, 2006, 11:13:41 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

ben2ong2

[ Continued from ~clarke/c++tips/manipulatorI. -adc ]


RESPONSE: You are not allowed to view links. Register or Login (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.)


You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login