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

标签 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 特化。

我是否需要为 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/

相关文章:

SQLite:如何交换仅留下 ID 列的两行

c++ - 在 Windows 上编译 MariaDB C/C++ 连接器

c++ - 如何在 C++ 中可视化/绘制图形?

c++ - 如何在 C++11 中初始化未在其构造函数中初始化其所有成员的类

c++ - std::vector< MyObj* > 到 std::vector< MyObj Const * >,如何没有循环?

java - 如何交换数组中最大的数字和最后一个数字?

c++ - 从内存缓冲区创建一个 fstream 对象

c++ - 读取 system() 命令错误响应消息

C++ 终止调用,没有事件异常

java - 链表中的交换节点溢出java