Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"using namespace" statement inside an anonymous namespace

Tags:

c++

namespaces

When using a using namespace statement inside an anonymous namespace bring the namespace used in to the file scope? Eg:

namespace foo
{
    int f() { return 1; }
}
namespace
{
    using namespace foo;
}
int a()
{
    return f(); // Will this compile?
}
like image 983
小太郎 Avatar asked Jan 08 '12 05:01

小太郎


2 Answers

According to 7.3.4 [namespace.udir] paragraph 4 a namespace directive is transitive:

For unqualified lookup 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.

... and according to 7.3.1.1 [namespace.unnamed] paragraph 1 there is kind of an implicit using directive for the unnamed namespace:

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, all occurrences of unique in a translation unit are replaced by the same identifier, and this identifier differs from all other identifiers in the entire program.

Thus, the answer is "yes, this is supposed to compile" (and it does with all C++ compilers I tried it with).

like image 177
Dietmar Kühl Avatar answered Oct 23 '22 12:10

Dietmar Kühl


Yes.

This is because an anonymous namespace is automatically brought into the containing scope.

like image 3
Drew Dormann Avatar answered Oct 23 '22 13:10

Drew Dormann