3

Effective c++ 第三版中的第 25条,Scott Meyers 建议在与类相同的命名空间中实现交换,然后在交换时使用 using std::swap,作者说:

例如,如果您要以这种方式编写交换调用:

std::swap(obj1,obj2);  // the wrong way to call swap

您将强制编译器仅考虑 std 中的交换,从而消除在其他地方定义更合适的 T 特定版本的可能性。唉,一些被误导的程序员确实有资格以这种方式调用交换,这就是为什么为你的类完全专门化 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);
}

为什么不在std::swap全局命名空间中?这样,添加自定义交换函数会更简单。

4

1 回答 1

7

可能是因为标准是这样说的,17.6.1.1/2:

除了宏、operator 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 {}

失败了

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);
于 2013-10-25T11:26:15.420 回答