问题
Here I write a code snippet to see which swap
would be called, but the result is neither. Nothing is outputted.
#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;
}
Which swap
is called? And in another circumstance, why is the specialized swap
without const
specifier called, not the ::swap
?
回答1:
std::swap()
is something like [ref]
template< class T >
void swap( T& a, T& b );
It is a better match than your
void swap(const Test& lhs, const Test& rhs);
for
swap(a, b);
where a
and b
are non-const. So std::swap()
is called, which outputs nothing.
Note that std::swap()
participates in overload resolution because of using namespace std;
.
来源:https://stackoverflow.com/questions/49646146/why-is-my-customed-swap-function-not-called