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

Why is my customed `::swap` function not called?

本文关键字:quot 调用 函数 我的 为什么 swap 自定义      更新时间:2023-10-16

在这里,我编写了一个代码片段来查看将调用哪个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;
}  

哪个swap叫?在另一种情况下,为什么被称为没有const说明符的专用swap,而不是::swap

std::swap()类似于[ref]

template< class T >
void swap( T& a, T& b );

它比你的更好匹配

void swap(const Test& lhs, const Test& rhs);

swap(a, b);

其中ab非恒常量。所以调用std::swap(),它不输出任何内容。

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