使用声明解决歧义 [英] Resolving ambiguity with using declaration
问题描述
看看这个片段:
namespace A {
int fn();
}
namespace B {
int fn();
}
// namespace Ns {
using namespace A;
using namespace B;
using A::fn;
int z = fn();
// }
此代码无法编译,因为 fn()
在 int z = fn();
This code doesn't compile, as fn()
is ambiguous at int z = fn();
如果我将使用,
和 z
放入命名空间(删除两个//
),则代码会编译.这是为什么?全局名称空间有什么特别之处?
If I put using
's and z
into a namespace (remove the two //
), the code compiles. Why is that? What is special about the global namespace?
推荐答案
请参阅[namespace.udir]/2
See [namespace.udir]/2
using-directive (使用指令)指定可以在以下范围内使用指定名称空间中的名称: using-directive 出现在 using-directive 之后.在不合格的名称查找(3.4.1)期间,出现名称就像它们是在包含 using-directive 和提名的名称空间.
A using-directive specifies that the names in the nominated namespace can be used in the scope in which the using-directive appears after the using-directive. During unqualified name lookup (3.4.1), the names appear as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace.
因此,当您拥有名称空间 Ns
时,指令使用名称空间A;
和使用名称空间B
会使 A ::fn
和 B :: fn
出现在全局名称空间中,而使用A :: fn;
会使 fn
出现在 Ns
.后者声明在名称查找期间获胜".
Thus, when you have the namespace Ns
, the directives using namespace A;
and using namespace B
make A::fn
and B::fn
appear in the global namespace, whereas using A::fn;
makes fn
appear in Ns
. The latter declaration "wins" during name lookup.
这篇关于使用声明解决歧义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!