命名空间
变体
操作

std::swap(std::variant)

来自 cppreference.cn
< cpp‎ | utility‎ | variant
 
 
 
 
定义于头文件 <variant>
template< class... Types >

void swap( std::variant<Types...>& lhs,

           std::variant<Types...>& rhs ) noexcept(/* see below */);
(C++17 起)
(C++20 起为 constexpr)

重载 std::swap 算法用于 std::variant。实际上调用 lhs.swap(rhs)

仅当 Types... 中所有 T_istd::is_move_constructible_v<T_i>std::is_swappable_v<T_i> 都为 true 时,此重载才参与重载决议。

目录

[编辑] 参数

lhs, rhs - 要交换值的 variant 对象

[编辑] 返回值

(无)

[编辑] 异常

noexcept 规范:  
noexcept(noexcept(lhs.swap(rhs)))

[编辑] 注意

特性测试 标准 特性
__cpp_lib_variant 202106L (C++20)
(DR)
完全 constexprstd::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++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
P2231R1 C++20 swap 不是 constexpr,而所需的运算在 C++20 中可以是 constexpr 设为 constexpr

[编辑] 另请参阅

与另一个 variant 交换
(public member function) [编辑]