Why is my custom function :: swap not called?

Here I am writing a piece of code to see which one swapwill be called, but the result will not. Nothing is output.

#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 one swapis being called? And in another case, why is it called specialized swapwithout a constspecifier, and not ::swap?

+4
source share
1 answer

std::swap()something like [ ref ]

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

It's better than yours

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

for

swap(a, b);

where aand b not const . So it is called std::swap()that does not output anything.

Please note that is std::swap()involved in resolving congestion due using namespace std;.

+13
source

Source: https://habr.com/ru/post/1695743/


All Articles