Why is the using directive using namespace std;
in when enclosed in an anonymous namespace behaves as if it appeared at global scope?
#include <iostream>
namespace x
{
using namespace std;
void g()
{
cout << 1;
}
}
int main()
{
cout << 1; // compiles fine if `namespace x` is replaced with `namespace`
}
An unnamed namespace is equivalent to essentially writing:
namespace __compiler_generated_unique {
}
using namespace __compiler_generated_unique;
So it's like having a using directive at global scope. And using directives are transitive.
For a normative reference, here it is from n4861 (The C++20 standard draft):
[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 tounique
.
[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.