0

I have a logging class with a std::stringstream member. I use it's output << overloading to get a nice easy means for catching all the data types std::stringstream gives me for free.

Here's the problem. After sending data into the stream, I want an easy way to flush it automatically to my destination (which is variable/dynamic in nature).

std::ostream will "auto flush" if you send an endl down it. That's and acceptable solution I would duplicate.

How can I implement that myself? Note that I don't want to override every operator<<() overload in std::stringstream!

πάντα ῥεῖ
  • 85,314
  • 13
  • 111
  • 183
BuvinJ
  • 9,113
  • 5
  • 74
  • 84

2 Answers2

1

I've done a similar thing. What I do is use an unnamed class instance to consume the output and put the flushing in the destructor. Something like this:

int i = 0;
MyClass() << "This is a log message containing an int: " << i;
// here, the class destructs and does whatever you need to do to flush the stream
Anon Mail
  • 4,575
  • 1
  • 17
  • 20
1

Instead of subclassing std::stringstream, it's prefered to use composition (see Composition over inheritance).

With this, your class would look like this:

class Log{

    std::stringstream _stream;

    [...] // Constructor and other class logic

    public:
    Log& operator<<(string s){
        _stream << s << endl;
        return *this;
    }

};
ZeroUltimax
  • 256
  • 1
  • 9
  • Thanks. I already have it as a member though, and my Log class is not what I << the data into. I send data directly to the member via an accessor. Ignoring that, your solution would force me to overload every version of the stringstream << function. That negates the entire purpose of using it! All I want it for is those dozens of "free" functions. – BuvinJ Mar 02 '17 at 19:33