tags:

views:

83

answers:

2

I'd like to write a simple ostream which wraps an argument ostream and changes the stream in some way before passing it on to the argument stream. The transformation is something simple like changing a letter or erasing a word

What would a simple class inheriting from ostream look like? What methods should I override?

+1  A: 

std::ostream is not the best place to implement filtering. It doesn't have the appropriate virtual functions to let you do this.

You probably want to write a class derived from std::streambuf containing a wrapped std::ostream (or a wrapped std::streambuf) and then create a std::ostream using this std::streambuf.

std::streambuf has a virtual function overflow which you can override and use to alter the bytes before passing them to the wrapped output class.

Charles Bailey
A: 

I've always thought that writing specialised streams is the wrong approach to almost any problem. The output stream is typically an end-point in your program - any data processing should be done long before you get to the stream itself. Similarly for input streams - putting the intelligence needed to (say) parse input in the stream is putting it in the wrong place. Just my 2 cents, of course.

anon
Definitely. It's may be a sensible place to plug byte filters such as compression or encryption (add these sort of features transparently to code that already serializes to ostream ), but it's probably not the correct place to be manipulating structured data.
Charles Bailey