c++ - 在 namespace 中搜索名称时是否有任何顺序?

标签 c++ namespaces

希望我不是在问一个愚蠢的问题。我确实在 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: 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)

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

我的问题是:

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

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

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

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

谢谢。

最佳答案

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++ - 在 namespace 中搜索名称时是否有任何顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16722043/

相关文章:

c++ - QTreeWidget : Windows Explorer-like editing

c - dlmopen() 无法解析创建的命名空间中定义的函数符号

c++ - 全局命名空间不在其他命名空间中检查

c# - 防止 Visual Studio 在复制粘贴时自动导入命名空间

c# - 命名空间范围

c++ - 正确转换为指向返回函数的函数的函数指针

c++ - 一对 vector 构造函数 : initializer list vs explicit construction

C++ 开发环境 Eclipse

c++ - 如何在 Debian 7 上安装 FFmpeg 开发者库

jquery - 如何在现有 Mootools 站点之上实现 jQuery