在有效c ++第三版中的第25项中,Scott Meyers建议在与该类相同的名称空间中实现交换,然后在交换时使用std :: swap进行使用,作者在其中说:
例如,如果要编写调用以这种方式交换:
Run Code Online (Sandbox Code Playgroud)std::swap(obj1,obj2); // the wrong way to call swap您将迫使编译器只考虑std中的swap,从而消除了获得在其他地方定义的更适合T特定版本的可能性。las,有些被误导的程序员确实以这种方式限定了调用的资格,这就是为什么为您的类完全专门化std :: swap如此重要的原因。
作者建议始终以这种方式交换对象:
#include <iostream>
#include <utility>
#define CUSTOM_SWAP
namespace aaa{
struct A
{
};
#ifdef CUSTOM_SWAP
void swap( A&, A& )
{
std::cout<<"not std::swap"<<std::endl;
}
#endif
}
int main()
{
using std::swap; // add std::swap to a list of possible resolutions
aaa::A a1;
aaa::A a2;
swap(a1,a2);
}
Run Code Online (Sandbox Code Playgroud)
为什么不在std::swap全局名称空间中?这样,添加自定义交换功能会更简单。
可能是因为该标准是这样,17.6.1.1/2:
除宏,运算符new和operator delete以外的所有库实体均在名称空间std或嵌套在名称空间std中的名称空间中定义。
而且您using ::swap有时仍需要放置,因此会引入更多特殊情况。这里我用func的不是swap- http://ideone.com/WAWBfZ:
#include <iostream>
using namespace std;
template <class T>
auto func(T) -> void
{
cout << "::f" << endl;
}
namespace my_ns {
struct my_struct {};
auto func(my_struct) -> void
{
cout << "my_ns::func" << endl;
}
auto another_func() -> void
{
// won't compile without `using ::func;`
func(123);
}
}
auto main() -> int {}
Run Code Online (Sandbox Code Playgroud)
失败于
prog.cpp: In function ‘void my_ns::another_func()’:
prog.cpp:21:17: error: could not convert ‘123’ from ‘int’ to ‘my_ns::my_struct’
func(123);
Run Code Online (Sandbox Code Playgroud)