希望我不是在问一个愚蠢的问题。我确实在 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
命名空间。
我的问题是:
在多个命名空间中搜索名称是否有顺序?
是否应该始终先搜索封闭命名空间,然后搜索全局命名空间?
如果是这种情况,为什么我们已经在
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/