Question

Possible Duplicate:
std::endl is of unknown type when overloading operator<<

#include <iostream>

using namespace std;

struct OutputStream
{
    template<class T>
    OutputStream& operator <<(const T& obj)
    {
        cout << obj;

        return *this;
    }
};

OutputStream os;

int main()
{    
    os << 3.14159 << endl; // Compilation Failure!
}

The VC++ 2012 compiler complains:

error C2676: binary '<<' : 'OutputStream' does not define this operator or a conversion to a type acceptable to the predefined operator

Was it helpful?

Solution

The reason is that the compiler cannot deduce the type of T, because std::endl is a function template defined as

template <class charT, class traits>
  basic_ostream<charT,traits>& endl ( basic_ostream<charT,traits>& os );

The way it is overcome in IOStreams is by providing an appropriate overload of operator<<:

OutputStream& operator <<(std::ostream& ( *pf )(std::ostream&))
{
  cout << pf;
  return *this;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top