std :: swap不会调用我的自定义交换实现c ++ 11

时间:2015-09-24 12:00:10

标签: c++ c++11 swap

我有这样的代码:

#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 specialization。

我是否需要为班级another进行自定义交换,或者我遗失了什么?

3 个答案:

答案 0 :(得分:6)

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
}

答案 1 :(得分:1)

您的swap期待thing。这是你想要的吗?

int main(int argc, char** argv){
    another a, b;

    using std::swap; // let the compiler decide which swap to use

    swap(a.a, b.a); // calls swap(thing & a, thing & b) and thing.swap
}

答案 2 :(得分:0)

您明确呼叫std::swap - 没有理由应该调用自定义方法。

但是如果你改变了这一点 - 请务必更改方法的界面 - 在这种形式下,编译错误将会发生。

相关问题