To create manipulators that take arguments other than int and long, you must use the IOMANIPdeclare macro, which declares the classes for your new type, as well as the OMANIP macro.
The following example uses a class money
, which is a long type. The setpic
manipulator attaches a formatting “picture” string to the class that can be used by the overloaded stream insertion operator of the class money
. The picture string is stored as a static variable in the money
class rather than as data member of a stream class, so you do not have to derive a new output stream class.
#include <iostream.h>
#include <iomanip.h>
#include <string.h>
typedef char* charp;
IOMANIPdeclare( charp );
class money {
private:
long value;
static char *szCurrentPic;
public:
money( long val ) { value = val; }
friend ostream& operator << ( ostream& os, money m ) {
// A more complete function would merge the picture
// with the value rather than simply appending it
os << m.value << '[' << money::szCurrentPic << ']';
return os;
}
friend ostream& setpic( ostream& os, char* szPic ) {
money::szCurrentPic = new char[strlen( szPic ) + 1];
strcpy( money::szCurrentPic, szPic );
return os;
}
};
char *money::szCurrentPic; // Static pointer to picture
OMANIP(charp) setpic(charp c)
{
return OMANIP(charp) (setpic, c);
}
void main()
{
money amt = 35235.22;
cout << setiosflags( ios::fixed );
cout << setpic( "###,###,###.##" ) << "amount = " << amt << endl;
}