I want to overload operator<< for my class. Should I add this overloaded definition to the std namespace? (since the ostream operator<< is part of the std namespace) Or should I just leave it in the global namespace?
In short:
class MyClass {
};
namespace std {
ostream& operator<< ( ostream& Ostr, const MyClass& MyType ) {}
}
OR
class MyClass {
};
std::ostream& operator<< ( std::ostream& Ostr, const MyClass& MyType ) {}
Which is more appropriate and why? Thanks in advance for your responses.
You should put the operator overload in the same namespace as your class.
This will allow the operator to be found during overload resolution using argument-dependent lookup (well, actually, since
ostreamis in namespacestd, the overload overload would also be found if you put it in namespacestd, but there is no reason to do that).From the point of view of good design practices, the operator overload is more a part of your class’s interface than the interface of
ostream, so it belongs in the same namespace as your class (see also Herb Sutter’s Namespaces and the Interface Principle).From the point of view of writing standards-compliant and portable code, you can’t put the operator overload into namespace
std. While you can add template specializations for user-defined entities to namespacestd, you can’t add additional function overloads.