0

I made my own stream class inherited from std::ostream with a template insertion operator:

class MyOstream : public std::ostream 
{
   ...
   template <typename T>
   std::ostream & operator << (T value)
   {
      ...
      return std::ostream::operator<<(value);
   }
}

Also, I have a function that gets a reference to a std::ostream as an argument:

void some_func(std::ostream & stream) 
{
   stream << "Hello World!";
}

I want to somehow call MyOstream::operator<<() in some_func(), but the problem is that std::ostream::operator<<() is not virtual (actually, there are multiple overloaded operators + several friend operators) and I can't override it as usual.

Is there any way to do this without changing the interface of some_func()?

Addition

Function some_func(...) gets an object of MyOstream class as a parameter.

Addition #2

Actually I have my own MyStreambuf inherited from std::streambuf, which provides all the logic, MyOstream class is just needed to access to binary data. MyStreambuf class is used to restrict size of data, that user can write (let it be 500B). So, if object of MyStreambuf currently contains 450B of data and user will try to write 100B it'll cause setting of std::ios_base::badbit and refusing data. If user then try to write 10B, which is absolutely valid, it fails, cause of badbit set. That is the real problem.

So, the real problem I'm trying to overcome is calling clear() before each attempt to write.

  • 3
    afaik `std::ostream` is not meant to be used as base class, but [`std::basic_ios`](https://en.cppreference.com/w/cpp/io/basic_ios) is. – 463035818_is_not_an_ai Aug 03 '21 at 15:52
  • 2
    there are only very few classes in the standard library that are meant to be inherited from. Don't use inheritance as the default goto solution – 463035818_is_not_an_ai Aug 03 '21 at 15:53
  • 2
    in different words: Why do you inherit from `std::ostream` ? The aim is to use `some_func` without modifying it, right? What is the actual stream you want to write to? – 463035818_is_not_an_ai Aug 03 '21 at 15:58
  • 1
    The usual way to handle this is to derive from `std::streambuf` instead, and then pass an instance of it to the constructor of a standard `std::ostream`. You can't override non-virtual `operator<<`, but you can still implement what actions are performed when the stream is written to. See [A custom ostream](https://stackoverflow.com/questions/13703823/) – Remy Lebeau Aug 03 '21 at 16:25
  • Do you have a reason to specialize `std::ostream` instead of `std::streambuf`? – Stephen M. Webb Aug 03 '21 at 16:26
  • First question to ask yourself is why you want your own stream class? And then ensure that it is in fact the proper solution for the problem you have. – Phil1970 Aug 03 '21 at 17:59

0 Answers0