20

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?
}
小太郎
  • 5,510
  • 6
  • 37
  • 48

3 Answers3

17

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).

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
3

Yes.

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

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
1

Yes, because, as Dietmar Kühl quoted, an anonymous namespace is replaced by its content.

However, you should pay attention that it is replaced exactly where it is declared (edit), so there is no "magic" in this. For example, this won't work:

namespace foo
{
    int f() { return 1; }
}

int a()
{
    return f(); // Will this compile?
}

namespace
{
    using namespace foo;
}
Mr Fooz
  • 109,094
  • 6
  • 73
  • 101
Tamer Shlash
  • 9,314
  • 5
  • 44
  • 82
  • An anonymous namespace is a proper namespace. Its initial declaration is replaced with the text he quoted, including a `using namespace` directive, but its body is not replaced with anything. – Potatoswatter Jan 08 '12 at 06:12
  • I take issue with "an anonymous namespace is replaced by it's content." The declaration and definition of a namespace are exactly the same thing. The content doesn't participate in any replacement. – Potatoswatter Jan 08 '12 at 06:33