不合格的名称查找:为什么本地声明对使用指令隐藏声明 [英] Unqualified name lookup: Why local declaration hides declaration from using directive
问题描述
考虑以下代码:
namespace A
{
int i = 24;
}
namespace B
{
using namespace A;
int i = 11;
int k = i; // finds B::i, no ambiguity
}
第6.4.1节不合格的名称查找[basic.lookup.unqual]
- 由使用指令提名的名称空间中的声明在包含使用指令的名称空间中可见;看 [namespace.udir].出于不限定名称查找规则的目的 在[basic.lookup.unqual]中进行了说明, using指令提名的名称空间被视为的成员 封闭名称空间.
对我而言,标准非常清楚地表明,出于不限定名称查找(int k = i
中的i
)的目的,A
中的i
声明被视为B
的成员,因此i
应该在int k = i
中不确定,但是gcc
和clang
编译并将i
解析为本地B::i
.我已经搜索了标准( basic.scope.hiding 和 namespace.udir ),但没有发现与以上之一.我发现这是用于合格名称查找的,但不是用于非合格名称查找的. p>
为什么i
明确?
关键是10.3.4/2在不限定名称的查找过程中,这些名称似乎是在最近的包含该名称的封闭命名空间中声明的,指令和指定的名称空间."
指定的名称空间是A,using指令在B中,最小的(实际上是唯一的)公共名称空间是全局名称空间.因此,i
看起来就像在全局名称空间中声明的一样,并被B::i
隐藏.
Consider this code:
namespace A
{
int i = 24;
}
namespace B
{
using namespace A;
int i = 11;
int k = i; // finds B::i, no ambiguity
}
§6.4.1 Unqualified name lookup [basic.lookup.unqual]
- The declarations from the namespace nominated by a using-directive become visible in a namespace enclosing the using-directive; see [namespace.udir]. For the purpose of the unqualified name lookup rules described in [basic.lookup.unqual], the declarations from the namespace nominated by the using-directive are considered members of that enclosing namespace.
For me the standard says pretty clear that for the purpose of unqualified name lookup (the i
in int k = i
) the declaration of i
from A
is considered member of B
so i
should be ambiguous in int k = i
, however both gcc
and clang
compile and resolve i
to the local B::i
. I have searched the standard (basic.scope.hiding and namespace.udir) and did not find an exception or a rule to contradict the above one. I have found that for qualified name lookup, but not for unqualified name lookup.
Why is i
unambiguous?
The key is 10.3.4/2 "During unqualified name lookup, the names appear as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace."
The nominated namespace is A, the using directive is in B, and the smallest (in fact only) common namespace is the global namespace. Thus i
appears as if declared in the global namespace, and is hidden by B::i
.
这篇关于不合格的名称查找:为什么本地声明对使用指令隐藏声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!