Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 998
scottxiao Avatar asked Dec 08 '22 15:12

scottxiao


1 Answers

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;.

like image 193
Lingxi Avatar answered Dec 10 '22 04:12

Lingxi