c++operator-overloadingfunction-pointersstdendl

std::endl is not working with overloaded operator<< though dedicated non template function is implemented


I have some Logging::Logger class with the following functions:

template<typename T>
const Logger& Logger::operator<<(const T& in) const {
    // ...
    return *this;
}

const Logger& Logger::operator<<(std::ostream& (*os)(std::ostream&)) {
    // ...
    return *this;
}

And the following code:

loggerInstance << "ID: " << 5 << endl;

And I'm getting the following error though all operators seems to be implemented:

error C2678: binary '<<': no operator found which takes a left-hand operand of type 'const Logging::Logger' (or there is no acceptable conversion)

Of course, without endl everything is working.

I've looked at the following answer:

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

What am I missing?


Solution

  • Because your overloaded operators return a const Logger &, it follows that they must be const class methods, in order for you to be able to chain them together:

    const Logger& Logger::operator<<(std::ostream& (*os)(std::ostream&)) const
    

    However, it's better if they were not const class members, and returned a Logger &, instead:

    template<typename T> Logger& Logger::operator<<(const T& in)
    
    Logger& Logger::operator<<(std::ostream& (*os)(std::ostream&))
    

    This would be because, presumably, operator<< would be modifying the Logger instance, in some way. If not, you can use const objects and methods, here.