c++operator-overloadingmanipulators

How to implement C++ stream manipulator endl correctly?


I'm trying to implement a manipulator for my stream class. I don't know much about manipulators, but I think I'm doing everything right. The relevant parts of the code are below:

class stream
{
public:
    stream& operator<<(bool b) { // send bool value and return *this; }
    stream& operator<<(const char str[]) { // send string and return *this }
}; 

inline stream& endl(stream& s) 
{
    return s << "\r\n";
}


class stream stream;

int main()
{
    stream << endl;
}

I don't know what I'm doing wrong, but instead of calling endl the compiler is calling stream::operator<<(bool). Any idea?


Solution

  • Seeing stream << endl; the compiler has to pick an overload from the operator <<s you provided. endl is not convertible to const char *, but it is convertible to bool, so that's what you get.

    You probably meant to add an overload

    stream& operator<<(stream &(*function)(stream &)) {
       return function(*this);
    }
    

    inside of class stream that handles function pointers correctly.