std::swap(std::variant)
来自 cppreference.cn
定义于头文件 <variant> |
||
template< class... Types > void swap( std::variant<Types...>& lhs, |
(since C++17) (constexpr since C++20) |
|
为 std::variant 重载 std::swap 算法。效果上调用 lhs.swap(rhs)。
此重载仅在 std::is_move_constructible_v<T_i> 和 std::is_swappable_v<T_i> 对于 Types...
中的所有 T_i
均为 true 时参与重载决议。
内容 |
[编辑] 参数
lhs, rhs | - | 要交换值的 variant 对象 |
[编辑] 返回值
(无)
[编辑] 异常
noexcept 规范:
noexcept(noexcept(lhs.swap(rhs)))
[编辑] 注解
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_variant |
202106L |
(C++20) (DR) |
完全 constexpr std::variant |
[编辑] 示例
运行此代码
#include <iostream> #include <string> #include <variant> void print(auto const& v, char term = '\n') { std::visit([](auto&& o) { std::cout << o; }, v); std::cout << term; } int main() { std::variant<int, std::string> v1{123}, v2{"XYZ"}; print(v1, ' '); print(v2); std::swap(v1, v2); print(v1, ' '); print(v2); std::variant<double, std::string> v3{3.14}; // std::swap(v1, v3); // ERROR: ~ inconsistent parameter packs }
输出
123 XYZ XYZ 123
[编辑] 缺陷报告
以下行为变更缺陷报告被追溯应用到先前发布的 C++ 标准。
DR | 应用到 | 已发布行为 | 正确行为 |
---|---|---|---|
P2231R1 | C++20 | swap 在 C++20 中本可为 constexpr,但并非如此 |
设为 constexpr |
[编辑] 参见
与另一 variant 交换(public member function) |