Do you prefer explicit namespaces or 'using' in C++?

前端 未结 8 902
旧巷少年郎
旧巷少年郎 2020-12-06 01:16

When using C++ namespaces, do you prefer to explicitly name them, like this:

std::cout << \"Hello, world!\\n\";

Or do you prefer

8条回答
  •  情深已故
    2020-12-06 01:44

    My general rule is always explicitly use the namespace in headers, and usually use using in the code. The reason for the former is to make it explicitly clear in every part of the definition what is being used, and the reason for the latter is that it makes it easy to use replacements from another namespace if that becomes necessary. i.e. if we want to start using foo::string instead of std::string we just need to update the header and the using statement rather than replacing every instance of std::string with foo::string in the code.

    Of course, that is less useful for classes that reside in the std:: namespace, since even if you replace one class you're still likely to use others in std, and may run into ambiguity issues, but that was just an example.

提交回复
热议问题