I have a weird operator<< overloading problem, for which I can't find a reason. The following code is an extraction of the problem. This code fails to compile using VS2015, g++ 5.4.0 and clang 3.8.0, so I assume it's not a compiler bug.
#include <iostream>
#include <stdexcept>
inline std::ostream &operator<<(std::ostream &o, const std::exception &ex) {
o << ex.what();
return o;
}
namespace ns {
struct Struct { int m; };
inline std::ostream &operator<<(std::ostream &o, const Struct &s) {
o << s.m;
return o;
}
void fn() {
std::cout << Struct{ 1 } << std::endl;
try {
throw std::runtime_error("...");
} catch (std::exception &ex) {
std::cout << ex << std::endl;
}
}
}
int main() {
return 0;
}
The compiler can't find the overloading of operator<< for std::exception (the line "std::cout << ex << std::endl;" fails). What especially confuses me is, if I either:
- remove the overloading operator<< for Struct or
- if I move all code from namespace ns to global namespace
the code compiles. What is the reason for this behavior?