Namespaces
Variants

std:: swap (std::variant)

From cppreference.net
Utilities library
ヘッダーで定義 <variant>
template < class ... Types >

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

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

std::swap アルゴリズムを std::variant に対してオーバーロードします。実質的には 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 ) ) )

注記

機能テスト マクロ 標準 機能
__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 constexpr ではなかったが、必要な操作はC++20で constexpr 化可能 constexpr 化された

関連項目

別の variant と交換する
(公開メンバ関数)