Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unnamed and Named Namespace Resolution

Tags:

c++

namespaces

Should a reference to a name that exists in both an unnamed namespace and the local named namespace result in a error for ambiguity or is the resolution well-defined? I'm seeing the following work fine on G++ and Clang, less well on MSVC.

namespace Foo
{
    class Bar
    {
    public:
        int x;
    };
}

namespace
{
    class Bar
    {
    public:
        int y;
    };
}

namespace Foo
{

void tester()
{
    Bar b;
}

}

int main()
{
    Foo::tester();
    return 0;
}
like image 635
Andrew Avatar asked Oct 19 '22 22:10

Andrew


1 Answers

GCC and Clang are right. Within Foo::tester, an unqualified use of Bar unambiguously refers to Foo::Bar.

Unqualified lookup is specified by C++11 3.4.1/1:

the scopes are searched for a declaration in the order listed in each of the respective categories; name lookup ends as soon as a declaration is found for the name.

The scopes searched for the use of a name in a function are listed in 3.4.1/6:

A name used in the definition of a function [...] that is a member of namespace N [...] shall be declared before its use in the block [...] or, shall be declared before its use in namespace N or, if N is a nested namespace, shall be declared before its use in one of N’s enclosing namespaces.

In this case, the function is a member of Foo, so Foo is searched before the enclosing (global) namespace, which includes the unnamed namespace. Foo::Bar is found there, and lookup ends.

like image 130
Mike Seymour Avatar answered Oct 23 '22 11:10

Mike Seymour