在名称空间中搜索名称时是否有任何顺序?

时间:2013-05-23 19:12:19

标签: c++ namespaces

希望我不是在问一个愚蠢的问题。我确实在谷歌搜索过但找不到太多信息。

我有以下简单的代码引自Herb Sutter的Exceptional C ++ Book Item 31:

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

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

编译时:

  

prog.cpp:在函数'int main()'中:
  prog.cpp:12:13:错误:调用重载'f(NS :: T&)'是不明确的   prog.cpp:12:13:注意:候选人是:
  prog.cpp:8:6:注意:void f(NS :: T)
  prog.cpp:4:10:注意:void NS :: f(NS :: T)

据我所知,这是因为f的参数依赖查找。编译器发现了f的两个版本,一个在全局命名空间中,一个在NS命名空间中。

我的问题是:

  1. 在多个名称空间中搜索名称时是否有任何顺序?

  2. 是否应始终先搜索封闭的命名空间,然后再搜索全局命名空间?

  3. 如果是这种情况,如果我们已在NS命名空间中找到匹配项,那么为什么仍然存在歧义?

  4. 如果我的问题不明确,请随时纠正我。

    谢谢。

1 个答案:

答案 0 :(得分:3)

3.4.2.3 [basic.lookup.argdep]似乎暗示ADL将在通常的非限定名称查找过程之后执行。

关于非限定名称查找的部分表明名称解析从最窄的范围开始并向外移动。

[ 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 ]