简体   繁体   English

c++ using 语句在 function 中,后跟 function 名称(用于 ADL?)

[英]The c++ using statement within a function, followed by a function name (for ADL?)

What is the copy-and-swap idiom? 什么是复制和交换成语? in this question, in the top answer, within the section where the swap public friend overload is implemented, the implementation makes use of this:在这个问题中,在最佳答案中,在实现交换公共朋友重载的部分中,实现使用了这个:

friend void swap(dumb_array& first, dumb_array& second){
    //the line of code below
    using std::swap;
    //then it calls the std::swap function on data members of the dumb_array`s
}

My question is the following: what is the using std::swap used for here (the answer mentions something related to enabling ADL);我的问题如下:这里using std::swap是什么(答案提到了与启用 ADL 相关的内容); what use case of "using" is specifically being invoked here and what are the effects of adding that line of code and the effects of not adding it on the code?这里专门调用了“使用”的什么用例,添加该行代码的效果是什么,以及不在代码上添加它的效果是什么?

The using statement makes this line work: using 语句使这条线工作:

swap(first, second);

Notice that we can omit std:: in front of swap .请注意,我们可以在swap前面省略std::

The important thing there is that std::swap(...) is a qualified lookup , but swap(...) is an unqualified lookup .重要的是std::swap(...)合格的查找,但swap(...)不合格的查找 The main difference is that qualified lookup is calling a function in a specific namespace or scope (the one specified), whereas unqualified lookup is a bit more flexible since it will look into parent scope of the current context and also the global namespace.主要区别在于合格查找在特定命名空间或 scope(指定的)中调用 function,而不合格查找更灵活一些,因为它将查找父 Z31A1FD140BE4BEF2D11E121EC9A1 的命名空间和全局命名空间。 In addition, unqualified lookup will also look into the scope of the type of the arguments.此外,不合格的查找还将查找 arguments 类型的 scope。 It's a nice tool, but also dangerous since it can call function from unexpected places.这是一个不错的工具,但也很危险,因为它可以从意想不到的地方调用 function。

ADL will only work with unqualified lookup, since it has to search for other namespaces and scopes. ADL 仅适用于非限定查找,因为它必须搜索其他名称空间和范围。

The using std::swap also ensure that if no function is found through ADL, it will call std::swap by default. using std::swap还确保如果通过 ADL 没有找到 function,它将默认调用std::swap

This idiom allow for user defined swap functions:这个习惯用法允许用户定义交换函数:

struct MyType {
    // Function found only through ADL
    friend void swap(MyType& l, MyType& r) {
        // ...
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM