Bad practice to declare names in the standard namespace?

前端 未结 5 768
轻奢々
轻奢々 2021-01-18 02:15

I was looking through the Google C++ style guide, and came across this:

\"Do not declare anything in namespace std, not even forward declarations of standard library

5条回答
  •  没有蜡笔的小新
    2021-01-18 02:54

    First of all, like much of the Google style guide, it's actually wrong. The standard specifically allows you to define a few specific entities in namespace std (e.g., specializations of existing templates over user defined types).

    Ignoring those exceptions, however, they do have the right general idea -- your code normally belongs somewhere other than namespace std. You can put it in the global namespace, or you can define another namespace, but you should leave std alone.

    You also should not try to forward-declare anything in the standard library. Standard functions are allowed (for example) to include extra parameters, as long as they include default values, so they can be invoked in the standard way. If you try to declare them yourself, instead of declaring the existing function, you could end up declaring an ambiguous overload instead.

    Bottom line: yes, use the standard library. When you do use it, get the declarations by including the standard header(s), not by trying to write your own.

提交回复
热议问题