views:

307

answers:

4

If I have have some overloaded ostream operators, defined for library local objects, is its okay for them to go to std namespace? If I do not declare them in std namespace, then I must use using ns:: operator <<.

As a possible follow-up question, are there any operators which should go to standard or global namespace?

+1  A: 

It is generally a bad practice to declare anything (types, operators, etc ...) to be a part of a namespace you do not own. This can have unexpected consequences for people consuming your library. A better solution is to define your own namespace and to import both std and your namespace when you need to combine solutions.

JaredPar
+11  A: 

According to Koenig Lookup (C++ Standard 3.4.2) operator<< will be searched in namespaces of arguments. No need to declare it in std namespace.

Kirill V. Lyadvinsky
so, if I have object/class from external C library in global namespace, should I declare operators in global namespace as well?
aaa
I think that it is a good idea to declare operators in namespace where its argument from.
Kirill V. Lyadvinsky
+3  A: 

The C++ Standard explicitly forbids you from declaring your own constructs in the std namespace.

John Dibling
std::swap is a notable exception. You are specifically allowed to provide template specialization of std::swap, which must reside in the std namespace
caspin
`std::swap` is no exception. You can provide specializations for any standard library templates.
Dennis Zickefoose
+8  A: 

operator<<( ..., MyClass ) should go in the same namespace as MyClass. You should think of it as part of the interface of MyClass, even though it happens to be (necessarily) a non-member function.

A couple of references:

Herb Sutter