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

不打扰是莪最后的温柔 提交于 2019-12-05 11:46:36

问题


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:


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.




回答2:


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."



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/2479253/which-namespace-does-operator-stream-go-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!