Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which namespace does operator<< (stream) go to?

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?

like image 954
Anycorn Avatar asked Mar 19 '10 17:03

Anycorn


2 Answers

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.

like image 72
Kirill V. Lyadvinsky Avatar answered Oct 14 '22 22:10

Kirill V. Lyadvinsky


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:

  • My article What's In a Class?.
  • C++ Coding Standards Item 57: "Keep a type and its nonmember function interface in the same namespace."
like image 37
Herb Sutter Avatar answered Oct 14 '22 20:10

Herb Sutter