Amir Saniyan
Amir Saniyan

Reputation: 13739

How can I derive my own stream from a standard stream?

How can I derive my own stream from a standard stream?

In C# language, there is a Stream class, but C++'s streams are too complex.

I want something like this:

class my_stream : public std::stream
{
  // How to derive?
};

void using_a_stream(std::stream* s)
{
  *s << "Hello world";
}

void main()
{
  std::stream s1;
  std::fstream s2("C:\\test.txt");
  my_stream s3;

  using_a_stream(&s1);
  using_a_stream(&s2);
  using_a_stream(&s3);
}

Note: The code just a sample and may be invalid C++ program. Thanks.

Upvotes: 7

Views: 5124

Answers (3)

wilx
wilx

Reputation: 18228

I think there are three levels of answer to this question:

Level 1: It is complicated, especially if you are completely new to C++, stop right now. Only if you feel adventurous, continue to level 2.

Level 2: Use some library that makes creating streams easier. I would suggest using Boost.IOStreams library. It makes creating own streams and streambufs much easier. If you are still not satisfied, continue to level 3.

Level 3: You will have to derive from std::streambuf and modify its behaviour to suit your needs. Then you will have to plug your streambuf into own stream.

Upvotes: 15

Thomas Berger
Thomas Berger

Reputation: 1870

Could you please describe a little bit more what you own streamclass should do? Just asking how without what is not the best way to get a constructive answer.

Maybe you should have a look at boost::iostream, as there is a much simpler and safer way to write own iostream classes.

Upvotes: 0

Related Questions