使用 using 指令进行不明确的名称查找

Ambiguous name lookup with using-directive

不允许将名称空间和同名的class放在一个声明区域中,即

namespace A {}
class A{};

is ill-formed(参见§3.3.1/4)。但是,可以通过 using 指令引入其中任何一个的名称:

namespace N { namespace A {int i;} }

struct A {static int i;};

using namespace N;

int i = A::i; // The global struct, or namespace N::A?

这段代码格式不正确吗? VC++ thinks so, as well as Clang:

main.cpp:7:9: error: reference to 'A' is ambiguous
int i = A::i;
        ^
main.cpp:3:8: note: candidate found by name lookup is 'A'
struct A {static int i;};
       ^
main.cpp:1:25: note: candidate found by name lookup is 'N::A'
namespace N { namespace A {int i;} }
                        ^

然而,GCC accepts it

谁是对的?

代码格式错误。查找 A 时,§7.3.4/6 中的步骤:

If name lookup finds a declaration for a name in two different namespaces, and the declarations do not declare the same entity and do not declare functions, the use of the name is ill-formed.

这里的命名空间是全局命名空间和N,实体是命名空间N::A和class::A.