Search code examples
c++stlstdiostreamstreambuf

Adapter for std streams


I have an abstract class in my project, its derivatives is used for input/output to different locations. It has virtual methods read and write.

virtual unsigned read(void *buf, unsigned len) = 0;
virtual void write(const void *buf, unsigned len) = 0;

I need a kind of an adapter between std streams (std::istream and std::ostream) and this class to redirect input/output to these methods.

So, for example, if

mystream << "some output";

is called, it will call the write method.

I guess i should overload std::istream and std::ostream or std::streambuf, but not sure which methods.

What is the better way to implement this?


Solution

  • There are lots of simple but not flexible ways of doing it. Most of these solution will not leverage istream or ostream. For instance, overloading the << operator is one way. The drawback is that you will have to implement this operator for all the usual types, and for all the standard manipulators, and so on. It may become a great burden.

    This is sad because the whole thing about istream and ostream is only to parse and format not to do input or output. The I/O responsibility is given to the streambuf. And your task calls for a custom implementation of streambuf which uses your read and write methods.

    The discussion is too long for such a small format as a stackoverflow answer but you can find good pointers in the following references.

    References

    Note

    As advised, using boost.iostreams maybe a good fit, but I don't know it enough.