Namespace lookup in C ++

I found a problem with finding a namespace. The following simplified code could not be compiled:

namespace A { namespace B { class Test { }; } namespace C { namespace B { typedef B::Test AnAlias; } } } 

The compiler complains that Test in the A::C::B namespace does not name the type.

The problem is that the compiler sees the namespace B inside the namespace C and is no longer looking for a search. I would suggest that he would also search in the namespace A (which is the encompassing namespace) and find B :: Test there.

If I rename C::B , everything will be fine.
If I qualify for A::B::Test , everything will be fine.
If I put a typedef directly in the A::C namespace, everything is fine.

This behavior was tested using the gcc 4.1 compiler and intel 12. (as for linux).

Are compilers right?

+4
source share
1 answer

B in typdef B::Test resolves to A::C::B If you intend to reuse the name B , you need to specify it to remove the ambiguity. Compilers behave correctly. IIRC, names are permitted to the closest declaration to its use or background information. In this case, A::C::B is the closest declaration to typedef .

+5
source

Source: https://habr.com/ru/post/1394405/


All Articles