加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – ADL是否适用于全局命名空间?

发布时间:2020-12-16 07:09:28 所属栏目:百科 来源:网络整理
导读:Examples such as启用std类型的输出解释了 ADL如何用于“注入”某个函数/运算符,具体取决于应用fn / op的类型. 我想知道ADL完全适用于全局命名空间,也就是说,在global namespace scope声明(或通过使用可用)的类型是否使ADL在全局命名空间中寻找匹配函数? 具
Examples such as启用std类型的输出解释了 ADL如何用于“注入”某个函数/运算符,具体取决于应用fn / op的类型.

我想知道ADL完全适用于全局命名空间,也就是说,在global namespace scope声明(或通过使用可用)的类型是否使ADL在全局命名空间中寻找匹配函数?

具体来说,这些是等价的. ADL?:

// 1 - at global namespace scope
struct GlobalType {};

template< class Ch,class Tr>
std::basic_ostream<Ch,Tr>& operator<<(std::basic_ostream<Ch,Tr>& os,GlobalType const& x)
{
    os << ...;
    return os;
} 

// 2 - within namespace
namespace ecaps {

    struct EcapsType {};

    template< class Ch,class Tr>
    std::basic_ostream<Ch,EcapsType const& x)
    {
        os << ...;
        return os;
    } 

}

// 3 - Type brought to global NS via using,function at global scope
namespace other {
    struct OtherType {};    
}

using other::OtherType;

template< class Ch,OtherType const& x)
{
    os << ...;
    return os;
}

WRT.全局命名空间范围不需要ADL :(在现在删除的答案后更新)

一个Daniel Krügler of Committee fame describes an ADL problem如此:

This unqualified call has the effect that unqualified name lookup
happens and as a consequence of this,the compiler searches for the
name operator<<. beginning from the lexical location where the
operator<< call is found “upwards”
(…) starting in the current namespace and all the
namespaces that include that namespace (including the global
namespace,btw.) and – …

EMPH.矿.请注意外部名称空间的描述如何仅被视为“……来自词汇位置……”.他继续:

… and – as a second route – it performs a second phase of this
lookup the compiler searches in the so-called associated namespaces of
the argument types occurring in this call.

In the presented example,the first phase of the search fails,because
at the point where #include <iterator> exists,there is no
corresponding operator<< for these argument types in any namespace.
Note that your declaration of operator<< is provided lexically after
the point where the call of operator<< happens somewhere in some of
the library headers. The second phase of the search would also
consider locations that
follow the actual function call
,but only within the associated namespaces.

大胆的恩赐.矿.因此,在我看来,ADL适用于全局命名空间是相关的.当然,我很容易误解一些事情.

注意:这可能是标准的一种情况,只是没有明确地以某种方式提及它,因为全局NS就像任何其他命名空间一样 – 然后它可能不会,我对标准的了解非常有限.

解决方法

完全忘记我最初的答案,这是完全错误的.

根据C 11标准,关于ADL的§3.4.2(强调我的):

When the postfix-expression in a function call (5.2.2) is an
unqualified-id,other namespaces not considered during the usual
unqualified lookup
(3.4.1) may be searched,and in those namespaces,
namespace-scope friend function declarations (11.3) not otherwise
visible may be found.

简而言之,由于非限定查找将始终在全局命名空间中进行搜索,因此ADL将永远不会应用于全局命名空间.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读