1)是正确 使用 的
swap。当您编写“库”代码并要在上启用ADL(依赖于参数的查找)时,请以这种方式编写
swap。另外,这与SFINAE无关。
// some algorithm in your pretemplate<class T>void foo(T& lhs, T& rhs){ using std::swap; // enable 'std::swap' to be found // if no other 'swap' is found through ADL // some pre ... swap(lhs, rhs); // unqualified call, uses ADL and finds a fitting 'swap' // or falls back on 'std::swap' // more pre ...}2)是
swap为您的课程提供功能的正确方法。
namespace Foo{class Bar{}; // dummyvoid swap(Bar& lhs, Bar& rhs){ // ...}}如果
swap现在按1)所示使用,则将找到您的功能。另外,如果您绝对需要,可以将该函数设为朋友,或者提供一个
swap由free函数调用的成员:
// version 1class Bar{public: friend void swap(Bar& lhs, Bar& rhs){ // .... }};// version 2class Bar{public: void swap(Bar& other){ // ... }};void swap(Bar& lhs, Bar& rhs){ lhs.swap(rhs);}3)您的意思是显式专业化。Partial仍然是其他东西,对于函数,仅结构/类,也是不可能的。因此,由于您不能专门
std::swap研究模板类,因此
必须
在名称空间中提供免费功能。如果我可以这么说,这不是一件坏事。现在,显式的专业化也是可能的,但是通常您不想对函数模板进行专业化:
namespace std{ // only allowed to extend namespace std with specializationstemplate<> // specializationvoid swap<Bar>(Bar& lhs, Bar& rhs){ // ...}}4)不,因为1)与2)和3)不同。同样,同时拥有2)和3)会导致总是选择2),因为它更合适。



