Tuesday, January 28, 2014

How does the name lookup work in this case?

Newsgroup: comp.lang.c++

Subject: How does the name lookup work in this case?

From: Peter <pilarp@...>

Date: Tue, 28 Jan 2014 12:47:31 -0800 (PST)



Consider this definition (namespace and class share the same name):



namespace Foo

{

int x;



class Foo

{

public:

static int x;

};



int Foo::x;

}



I wondered what Foo::x would refer to with "using" directive used for namespace Foo: a global variable x in namespace Foo or static member of class Foo? Basically, I assumed the following code would not compile:



int main()

{

using namespace Foo;

Foo::x;

return 0;

}



My reasoning went like this:



- Foo::x is a global variable x from namespace Foo

- Foo::Foo::x is a static member of class Foo from namespace Foo, but since

"using" directive is applied, the namespace name can be omitted, thus Foo::x is also a static member of class Foo

- conclusion: call to Foo::x in main() is ambiguous - it refers to two different entities



However, the compiler I tested it with (one of g++ recent versions) had no trouble disambiguating this: experiments showed Foo::x in main() is interpreted as global variable x in namespace Foo. Moreover, if I remove the definition of global x from namespace Foo, then the compiler emits the following error:



main.cpp: In function 'int main()':

main.cpp:16:4: error: 'x' is not a member of 'Foo'

Foo::x;



so it doesn't find the static member of class Foo. In order for the compiler to find it I have to qualify it fully as Foo::Foo::x despite the "using namespace Foo;" line. Why? How does the lookup work here?







via Usenet Forums - Usenet Search,Free Usenet - comp.lang.c++ http://ift.tt/1floQ5s

View all the progranning help forums at:

http://ift.tt/1dP9txN

No comments:

Post a Comment