I want to overload operator<<
for my class. Should I add this overloaded definition to the std
namespace? (since the ostream operator&l
Don't add it to the std
namespace, place it in the same namespace as your class. The purpose of a namespace is to prevent collisions. The standard says
17.4.3.1 Reserved names
It is undefined for a C++ program to add declarations or definitions to namespace std or namespaces within namespace std unless otherwise specified. A program may add template specializations for any standard library template to namespace std. Such a specialization (complete or partial) of a standard library template results in undefined behavior unless the declaration depends on a user-defined name of external linkage and unless the specialization meets the standard library requirements for the original template.
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 ostream
is in namespace std
, the overload overload would also be found if you put it in namespace std
, 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 namespace std
, you can't add additional function overloads.
Don't add to the standard namespace. Reason : If everybody did this, the standard namespace would have heaps of name clashes, which defeats the purpose of a namespace.
Your objective is for your class to be "ostream-able". It does not need to be in the standard namespace to do that. As long as it is in whatever namepsace your class is declared in, you're fine. Putting it in the standard namespace would be bad practice.