Search code examples
c++templatesoperator-overloadingwrapperostream

Getting ostream's Insertion Operators


I have a class that I want to wrap an ostringstream. I've gone about it like this:

class Foo {
    ostringstream os;
public:
    template <typename T>
    decltype(ostream() << T(), Foo)& operator <<(const T& param) {
        os << param;
        return *this;
    }
}

My intent there is that I'd get any operator defined for ostream for free. But I'm getting the compilation error:

error C2893: Failed to specialize function template unknown-type &Foo::operator <<(const T &)

Am I using the decltype wrong or something?


Solution

  • std::ostream does not have a default constructor, and Foo is not an expression that can be used in decltype. Instead, you can directly use os in the first expression. In order to return Foo& easier I'd use a trailing return type and use *this.

    template <typename T>
    auto operator<<(const T& param) -> decltype(os << param, *this);