I'd like to write a simple ostream
which wraps an argument ostream
and changes th开发者_如何学Pythone 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?
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.
Consider using Boost.Iostreams
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.
精彩评论