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

前端 未结 8 883
旧巷少年郎
旧巷少年郎 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:53

    I only use explicit namespaces when there's some ambiguity. It is more readable, but the extra typing is too tedious, and you have to assume other developers have a baseline level of familiarity with standard libraries.

    The only other times I spell out a namespace are when I'm only using it once or twice, like adding in a quick debug statement, or if I'm using some non-standard library.

    I typically declare the namespace at file scope, but if you're mixing namespaces it might make sense to put the declaration closer to the point where it's used, in function scope.

    0 讨论(0)
  • 2020-12-06 01:53

    I tend to explicitly import the names that I need at the top of the .cpp file, so...

    using std::cout; using std::endl;

    etc...

    That way I have control over the names that I use and it's easy to see where they come from and the code isn't cluttered at the point of use.

    In the rare cases where I am using two names from different namespaces I fully qualify them at the point of use.

    I always use fully qualified names in headers and hardly ever use 'using namespace x' anywhere...

    0 讨论(0)
提交回复
热议问题