为什么我的自定义`:: swap`函数没有被调用?

big*_*iao 4 c++ templates specialization

在这里,我编写了一个代码片段来查看哪个swap将被调用,但结果都不是.什么都没输出.

#include<iostream>
class Test {};
void swap(const Test&lhs,const Test&rhs)
{
    std::cout << "1";
}

namespace std
{
    template<>
    void swap(const Test&lhs, const Test&rhs)
    {
        std::cout << "2";
    }
    /* If I remove the const specifier,then this will be called,but still not the one in global namespace,why?
    template<>
    void swap(Test&lhs, Test&rhs)
    {
        std::cout << "2";
    }
    */
}
using namespace std;

int main() 
{
    Test a, b;
    swap(a, b);//Nothing outputed
    return 0;
}  
Run Code Online (Sandbox Code Playgroud)

swap被称为?而在另一种情况下,为什么swap没有const说明的专业人士,而不是::swap

Lin*_*gxi 13

std::swap()就像[ 参考 ]

template< class T >
void swap( T& a, T& b );
Run Code Online (Sandbox Code Playgroud)

这是一个比你的更好的匹配

void swap(const Test& lhs, const Test& rhs);
Run Code Online (Sandbox Code Playgroud)

对于

swap(a, b);
Run Code Online (Sandbox Code Playgroud)

其中,ab非常量.所以std::swap()被称为,什么都不输出.

请注意,std::swap()由于参与重载解析using namespace std;.

  • @bigxiao是最贴近你的变量的最专业的首选.变量最专业的匹配是非const版本,因为你的变量也是非常量的. (7认同)