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

ⅰ亾dé卋堺 提交于 2019-12-23 15:27:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!