stream manipulators which take arguments: HELP!

Leo Willems leo at atcmp.nl
Wed Jul 25 18:42:16 AEST 1990


>From article <331 at ndla.UUCP>, by platt at ndla.UUCP (Daniel E. Platt):
> Hi, 
> 
> I'd like some information on how to write stream manipulators which
> takes arguments.  All of the documentation I currently have on C++ 2.0
> doesn't cover it (I can't really call it 'documentation,' but its what
> I have at the moment).  
> 
> If anybody could send a quick sample (perhaps a skeleton) I'd appreciate it.
> 
> Dan Platt

This should work:

===================================================
#include <stream.h>
#include "iomanip.h"

typedef ostream& (*spfunc)(ostream&, int);

class Iomanip{
	friend ostream& operator<<(ostream&, Iomanip);
	friend Iomanip setspeed(int);

	Iomanip(spfunc f, int s) : sf(f), speed(s){}

	spfunc sf;
	int speed;
};

ostream&
operator<<(ostream& os, Iomanip im)
{
	return im.sf(os, im.speed);
}

ostream&
iospeed(ostream& os, int speed)
{
	os << "setting speed (ioctl stuff) to: " << speed << "\n";
	return os;
}

Iomanip
setspeed(int speed)
{
	return Iomanip(iospeed, speed);
}

main()
{
	cout << setspeed(9600) << "hello\n";
}
========================================

The basic idea from this example comes from Dewhurst & Stark.
(ISBN 0-13-723156-3, Programming in C++, p 189).

Leo


 Leo Willems			Internet: leo at atcmp.nl
 AT Computing			UUCP:     mcsun!hp4nl!kunivv1!atcmpe!leo
 P. O. Box 1428				
 6501 BK  Nijmegen		Phone:    +31-80-566880
 The Netherlands		Fax:	  +31-80-555887



More information about the Comp.unix.i386 mailing list