使用std :: swap禁用ADL

问题描述 投票:0回答:1

我以为using std::swap的要点是,如果我们交换某个类,交换将搜索定义该类的名称空间,否则它将使用std :: swap.so,我编写一些代码对其进行测试。

namespace np{
    class myclass{
        ...
    };
    void swap(const myclass&lhs,const myclass&rhs){
        cout<<"np::swap()"<<endl;
    }
}


int main()
{
   np::myclass m1,m2;
   using std::swap;
   swap(m1,m2);
}

但是结果使我感到困惑。它直接使用std :: swap,有人可以解释为什么吗?谢谢。

c++ swap argument-dependent-lookup
1个回答
1
投票

在重载解析中,您的swap将相对于std::swap松散,因为std::swap将参数作为非const引用,而您的函数将其作为const引用,这使匹配更差。

只需删除参数中的const,您的ADL重载将是首选。

© www.soinside.com 2019 - 2024. All rights reserved.