使用 std::swap 禁用 ADL

using std::swap disabled ADL

我认为 using std::swap 的要点是如果我们交换一些 class,交换将搜索定义 class 的命名空间,否则它使用 std::swap.所以我写了一些代码来测试它。

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);
}

但结果混淆me.it直接使用std::swap,谁能解释为什么?谢谢。

更新

如果函数寻找更好的匹配,为什么下面的代码输出 "inside",它看起来像使用声明隐藏全局 foo,这是更好的匹配

namespace np{
    class myclass{
        //...
    };
    void  foo(const myclass&m){
        cout<<"inside";
    }

}
void foo(np::myclass &m){
    cout<<"global";
}

int main()
{
   np::myclass m;
   using np::foo;
   foo(m);
} 

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

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

实际上,采用 const 个参数的 swap 函数无论如何都没有多大意义。