std::iter_swap 需要 ValueSwappable args vs std::swap 需要 Move A
std::iter_swap requires ValueSwappable args vs std::swap requires Move Assignable args
我很难理解为什么在下面的代码中直接调用std::swap()
会导致编译错误,而使用std::iter_swap
编译没有任何错误。
从iter_swap()
与swap()
- 有什么区别?,iter_swap
最终打电话给std::swap
但他们的行为仍然不同。
#include <iostream>
#include <vector>
class IntVector {
std::vector<int> v;
IntVector& operator=(IntVector); // not assignable
public:
void swap(IntVector& other) {
v.swap(other.v);
}
};
void swap(IntVector& v1, IntVector& v2) {
v1.swap(v2);
}
int main()
{
IntVector v1, v2;
// std::swap(v1, v2); // compiler error! std::swap requires MoveAssignable
std::iter_swap(&v1, &v2); // OK: library calls unqualified swap()
}
在 iter_swap
内部调用的swap
不是完全限定的,即不称为std::swap
,而是swap
。因此,在名称查找和ADL
编译器会找到多个与调用swap
匹配的函数。但是,overload resolution
会选择您提供的swap
,因为它最匹配。
如果您在主代码中使用swap
,那么它会编译得很好,因为它找不到std::swap
。即使您执行using namespace std;
,它也会编译
相关文章:
- a,b = b,a in python vs std::swap() in C++
- 使用 std::swap 禁用 ADL
- 如何使用 std::swap with array?
- 智能指针的 std::swap 是否保证引用保持不变?
- "std::swap"应用于这些对象时会做什么?
- 为什么 std::swap 不使用 swap 习语?
- 为什么有这么多std::swap的专业化
- 为什么使用std::swap不会在外部范围中隐藏其他交换函数
- 在结构C++中使用 std::swap 与 std::vector
- 为什么 std::swap 不适用于地址运算符
- std::swap vs std::exchange vs swap operator
- 使用静态tmp变量为简单类型C++重新实现std::swap()
- 使用 GCC 4.8 编译时无法对向量执行 std::swap
- 可以将"using std::swap;"放在标题中吗?
- "using std::swap"如何启用 ADL?
- std::swap 在 VS 2013 中导致无限递归
- 为什么不是 std::swap 在全局命名空间中
- std::swap(*(void **)x, *(void **)y)y是什么意思
- 在向量之间使用 std::swap 或 vector::swap
- 为什么 std::swap 不适用于模板项