taocp
taocp

Reputation: 23644

Is there any order when searching names in namespaces?

Hope that I am not asking a dumb question. I did search it in Google but couldn't find much information.

I have the following simple code quoted from Exceptional C++ Book Item 31 by Herb Sutter:

namespace NS
{
    class T{};
    void f(T);
}

void f(NS::T);
int main()
{
    NS::T params;
    f(params);
}

When I compiled it:

prog.cpp: In function ‘int main()’:
prog.cpp:12:13: error: call of overloaded ‘f(NS::T&)’ is ambiguous
prog.cpp:12:13: note: candidates are:
prog.cpp:8:6: note: void f(NS::T)
prog.cpp:4:10: note: void NS::f(NS::T)

I understand that it is because of argument dependent lookup for f. The compiler found two version of f, one in global namespace, one in NS namespace.

My question are:

  1. Is there any order when searching for a name in multiple namespaces?

  2. Should it be always searching for enclosing namespace first then to global namespaces?

  3. If this is the case, why there is still ambiguity if we already found a match in NS namespace?

Please feel free to correct me if my questions are not clear.

Thank you.

Upvotes: 3

Views: 255

Answers (1)

Steven Maitlall
Steven Maitlall

Reputation: 787

3.4.2.3 [basic.lookup.argdep] seems to imply that ADL will be performed after the usual unqualified name lookup procedure.

The section on unqualified name lookup indicates that name resolution starts at the narrowest scope and moves outward.

[ Example:
class B { };
namespace M {
   namespace N {
      class X : public B {
         void f();
      };
   }
}
void M::N::X::f() {
   i = 16;
}
// The following scopes are searched for a declaration of i:
// 1) outermost block scope of M::N::X::f, before the use of i
// 2) scope of class M::N::X
// 3) scope of M::N::X’s base class B
// 4) scope of namespace M::N
// 5) scope of namespace M
// 6) global scope, before the definition of M::N::X::f
—end example ]

Upvotes: 4

Related Questions