【问题标题】:Is there any order when searching names in namespaces?在命名空间中搜索名称时是否有任何顺序?
【发布时间】:2013-05-19 07:00:27
【问题描述】:

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

我引用了 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 命名空间中找到匹配项,为什么仍然存在歧义?

如果我的问题不清楚,请随时纠正我。

谢谢。

【问题讨论】:

  • 有些相关 - 仅当搜索在第一个匹配时停止时,顺序才相关。

标签: c++ namespaces


【解决方案1】:

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 ]

【讨论】:

  • 感谢您参考 C++ 标准,以便我可以阅读更多相关信息。
猜你喜欢
  • 1970-01-01
  • 2021-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
  • 2017-05-04
相关资源
最近更新 更多