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

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

这里我写了一段代码看看会调用哪个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);

其中 abnon-const。所以 std::swap() 被调用,它什么都不输出。

注意 std::swap() 因为 using namespace std; 而参与重载决策。