0

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?

Community
  • 1
  • 1
Mugen
  • 8,301
  • 10
  • 62
  • 140

1 Answers1

3

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.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148