shoosh
shoosh

Reputation: 79003

Writing an ostream filter?

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?

Upvotes: 5

Views: 1800

Answers (3)

dangerousdave
dangerousdave

Reputation: 6408

Consider using Boost.Iostreams

Upvotes: 0

anon
anon

Reputation:

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.

Upvotes: -1

CB Bailey
CB Bailey

Reputation: 792497

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.

Upvotes: 3

Related Questions