不合格的名称查找:为什么本地声明对使用指令隐藏声明 [英] Unqualified name lookup: Why local declaration hides declaration from using directive

查看:90
本文介绍了不合格的名称查找:为什么本地声明对使用指令隐藏声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

namespace A
{
   int i = 24;
}

namespace B
{
    using namespace A;
    int i = 11;

    int k = i; // finds B::i, no ambiguity
}

basic.lookup.unqual.2 :

第6.4.1节不合格的名称查找[basic.lookup.unqual]

  1. 由使用指令提名的名称空间中的声明在包含使用指令的名称空间中可见;看 [namespace.udir].出于不限定名称查找规则的目的 在[basic.lookup.unqual]中进行了说明, using指令提名的名称空间被视为的成员 封闭名称空间.

对我而言,标准非常清楚地表明,出于不限定名称查找(int k = i中的i)的目的,A中的i声明被视为B的成员,因此i应该在int k = i中不确定,但是gccclang 编译并将i解析为本地B::i.我已经搜索了标准( basic.scope.hiding namespace.udir ),但没有发现与以上之一.我发现这是用于合格名称查找的,但不是用于非合格名称查找的.

为什么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
}

And basic.lookup.unqual.2:

§6.4.1 Unqualified name lookup [basic.lookup.unqual]

  1. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆