4

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?

max_hassen
  • 387
  • 1
  • 5
  • 16
  • possible duplicate of [overloading '<<' with inhertiance and polymorphism?](http://stackoverflow.com/questions/11905648/overloading-with-inhertiance-and-polymorphism) – NathanOliver Sep 15 '15 at 14:25

3 Answers3

4

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.

fjardon
  • 7,921
  • 22
  • 31
  • Thank you. Yes, custom implementation of `streambuf` is exactly what i needed. The book of yours turned out pretty helpful well-explaining how `streambuf` works. – max_hassen Sep 16 '15 at 10:14
2

You might want to take a look at the boost iostreams library. It provides a framework that makes it easier to define iostreams with custom sources and sinks (input and output devices).

mattnewport
  • 13,728
  • 2
  • 35
  • 39
0

I am a fan of std::stringstream, and perhaps your class could make use of it.

std::stringstream ss;

ss << "some output";

from which something would invoke write like:

write(ss.str().c_str(),  ss.str().size());

You will have to figure out how to connect the two, but this has the advantage of providing all stream io.

On the other hand, directly implementing operator << and >> is not too difficult.

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

Start with the method you need first, then add functionality as you identify the requirements.

2785528
  • 5,438
  • 2
  • 18
  • 20