Compiling the following code fails because the second function can't find the first one, even though it's outside namespaces. I couldn't figure out the problem myself, and so far I haven't found any answers on the net.
test.cpp:
#include <bits/stdc++.h>
struct myclass {};
template <typename T, typename U>
std::ostream& operator<< (std::ostream &os, const std::pair<T, U> &p) {
os << "(" << p.first << ", " << p.second << ")";
return os;
}
namespace my {
void operator<< (std::ostream os, myclass m) {
std::cout << std::pair<int, int>(5, 4); // This is line 13.
}
}
int main() {
return 0;
}
Error given by the compiler (g++ test.cpp -O2 -o test.exe
):
test.cpp:13:13: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'std::pair<int, int>')
.
And it goes on, giving a long list of suggestions for what operator<<
could have meant.
Observation 1: If the two functions differ in name, no error occurs.
Observation 2: If namespace my {
}
is removed, no error occurs.
::operator<<(std::cout, std::pair<int, int>(5, 4));
it should work, but that's mighty ugly (and un-chainable). I won't post that as an answer in case there's a better way. – Stephanystephenusing ::operator<<;
). As to why the lookup doesn't end up finding the canidate in global namespace... – Scientific