C ++ wrapper class for iostream, use stream modifiers like std :: endl with operator <<

I am currently writing a wrapper for std::stringstream, and I want to forward all calls operator<<through my class to std::stringstream. This works fine now (thanks to this question: wrapper class for STL stream: direct operator <<calls ), but there is still one problem with it.

Let's say I have the following code:

class StreamWrapper {
private:
    std::stringstream buffer;
public:
    template<typename T>
    void write(T &t);

    template<typename T>
    friend StreamWrapper& operator<<(StreamWrapper& o, T const& t);

    // other stuff ...
};


template<typename T>
StreamWrapper& operator<<(StreamWrapper& o, T const& t) {
    o.write(t);
    return o;
}

template<typename T>
void StreamWrapper::write(T& t) {
    // other stuff ...

    buffer << t;

    // other stuff ...
}

If I do this now:

StreamWrapper wrapper;
wrapper << "text" << 15 << "stuff";

This works great. But if I want to use stream modifiers, such as std::endl, which is a function according to http://www.cplusplus.com/reference/ios/endl , I just do not compile.

StreamWrapper wrapper;
wrapper << "text" << 15 << "stuff" << std::endl;

Why? How can I redirect stream modifiers?

+5
2

. .

typedef std::ostream& (*STRFUNC)(std::ostream&);

StreamWrapper& operator<<(STRFUNC func)  // as a member, othewise you need the additional StreamWrappe& argument first
{
  this->write(func);
  return *this;
}
+3

, , . :

class StreamWrapper
{
    // ...
public:
    template <typename T>
    StreamWrapper& operator<<( T const& obj )
    {
        //  ...
    }
};

. , , . :

StreamWrapper& operator<<( std::ostream& (*pf)( std::ostream& ) )
{
    //  For manipulators...
}

StreamWrapper& operator<<( std::basic_ios<char>& (*pf)( std::basic_ios<char>& )
{
    //  For manipulators...
}

, .

( , , std::setw(int).)

+2

All Articles