我有这样的代码:
#include <utility>
#include <iostream>
struct thing {
void swap(thing & other){
std::cout << "swap method" << std::endl;
}
};
void swap(thing & a, thing & b) {
std::cout << "swap function" << std::endl;
a.swap(b);
}
struct another{
thing a;
};
int main(int argc, char** argv){
another a, b;
std::swap(a, b);
}
如果执行,它什么都不打印——例如它不使用我的“自定义”swap
。
我读到我不应该 std::swap 特化。
我是否需要为 another
类做自定义交换,或者我遗漏了什么?
最佳答案
std::swap
不会调用您的 swap
实现。你应该做的(在通用代码中)是让重载决议选择你自己的:
namespace stuff
{
struct foo { void swap(foo& other); };
swap(foo& lhs, foo& rhs) { lhs.swap(rhs); }
}
int main()
{
foo a, b;
int i = 0;
int j = 42;
using std::swap;
swap(i, j); // calls std::swap
swap(a, b); // calls stuff::swap(stuff::foo&, stuff::foo&) via ADL
}
关于c++ - std::swap 不调用我的自定义交换实现 c++11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32760771/