Why is operator<< overload not found?

Viewed 207

I've declared an operator<< overload for time_point in the global namespace and also one for a::Foo in the a namespace. When I try to print a time_point in a function also defined in namespace a, I get the error:

Invalid operands to binary expression.

Why is this, and what is the best solution?

#include <iostream>
#include <chrono>

std::ostream &operator<<(std::ostream &os,
                         const std::chrono::system_clock::time_point &time_point);
namespace a {
class Foo;
std::ostream &operator<<(std::ostream &os, const a::Foo &foo);
void print_time() {
  std::cout << std::chrono::system_clock::now(); // error here!
}
}

int main() {
  a::print_time();
}
1 Answers

The reason is simple: a::operator<< shadows your ::operator<< since they have the same name. This is why operators basically have to share a namespace with their classes: such shadowing is to be expected, and so ADL (as discussed in the comments) is the only reliable means of finding them.

Related