未命名命名空间中“使用命名空间”的范围

Scope of `using namespace` in Unnamed Namespace

为什么 中的 using 指令 ​​using namespace std; 当包含在匿名命名空间 中时,其行为就好像它出现在全局范围内一样?

#include <iostream>

namespace x
{
  using namespace std;
  void g()
  {
    cout << 1;
  }
}

int main()
{
  cout << 1; // compiles fine if `namespace x` is replaced with `namespace`
}

未命名的命名空间等同于本质上是这样写的:

namespace __compiler_generated_unique {

}
using namespace __compiler_generated_unique;

所以这就像在全局范围内使用 using 指令。并且 using 指令是可传递的。


规范参考,这里是n4861(C++20标准草案):

[namespace.unnamed]

1 An unnamed-namespace-definition behaves as if it were replaced by

inline namespace unique { /* empty body */ }
using namespace unique ;
namespace unique { namespace-body }

where inline appears if and only if it appears in the unnamed-namespace-definition and all occurrences of unique in a translation unit are replaced by the same identifier, and this identifier differs from all other identifiers in the translation unit. The optional attribute-specifier-seq in the unnamed-namespace-definition appertains to unique.

[namespace.udir]

4 For unqualified lookup ([basic.lookup.unqual]), the using-directive is transitive: if a scope contains a using-directive that nominates a second namespace that itself contains using-directives, the effect is as if the using-directives from the second namespace also appeared in the first.