I am using a library that defines output stream operators (operator<<) in the global namespace. In my own namespace, I was always declaring such operators in the global namespace, and never had problems with them. But now for various reasons I need to declare those operators in my own namespace, and suddenly, the compiler can't seem to find the operators declared in the library anymore.
Here's a simple example that illustrates my problem:
#include <iostream>
namespace A
{
struct MyClass {};
}
std::ostream & operator<<( std::ostream & os, const A::MyClass & )
{ os << "namespace A"; return os; }
namespace B
{
struct MyClass {};
std::ostream & operator<<( std::ostream & os, const B::MyClass & )
{ os << "namespace B"; return os; }
}
namespace B
{
void Test()
{
std::cout << A::MyClass() << std::endl;
std::cout << B::MyClass() << std::endl;
}
}
int main()
{
B::Test();
return 1;
}
I am getting the following error:
error: no match for ‘operator<<’ in ‘std::cout << A::MyClass()’
Note that if both operators are within the namespaces, or alternatively if they are both in the global namespace, the code compiles and executes correctly.
I'd really like to understand what's going on and also what the "good practice" for defining such operators with namespaces.
Thanks!
See Question&Answers more detail:os