首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Swappable

此类型的任何lvalue或rvalue都可以使用非限定函数调用与任何lvalue或其他类型的rvalue交换。swap()在这两种情况下std::swap和用户定义的swap()是可见的。

所需

如果对于U型的任何对象u和T型的任何对象t,则U型可替换为T型,

Expression

Requirements

Semantics

#include <utility> using std::swap; swap(u, t);

After the call, the value of t is the value held by u before the call, and the value of u is the value held by t before the call.

Calls the function named swap() found by overload resolution among all functions with that name that are found by argument-dependent lookup and the two std::swap templates defined in the header <utility>.

#include <utility> using std::swap; swap(t, u);

same

same

许多标准库函数%28--例如,许多算法(%29)--希望它们的参数满足Swappable,这意味着每当标准库执行交换时,它都使用等效的usingstd::swap; swap(t, u);...

典型的实现也是如此。

1%29在封闭的命名空间中定义非成员交换空间,如果需要访问非公共数据成员,则可以将其转发给成员交换空间。

2%29定义朋友函数在类中%28中,这种方法隐藏了类特定的交换,而不是adl%29的名称查找。

注记

未具体说明是否<utility>实际上在标准库函数执行交换时包含,因此用户提供的swap()不应该期望它被包括在内。

二次

代码语言:javascript
复制
#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()
}

二次

另见

is_swappable_withis_swappableis_nothrow_swappable_withis_nothrow_swappable (C++17)(C++17)(C++17)(C++17)

checks if objects of a type can be swapped with objects of same or different type (class template)

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com