Namespaces
Variants

swap(std::expected)

ja.cppreference.net より
 
 
ユーティリティライブラリ
言語サポート
型サポート (基本型、RTTI)
ライブラリ機能テストマクロ (C++20)
プログラムユーティリティ
可変長引数関数
コルーチンサポート (C++20)
契約サポート (C++26)
三方比較
(C++20)
(C++20)(C++20)(C++20)    
(C++20)(C++20)(C++20)

汎用ユーティリティ
関係演算子 (C++20で非推奨)
整数比較関数
(C++20)(C++20)(C++20)    
(C++20)
swap および 型操作
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
共通のボキャブラリ型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)



 
 
friend constexpr void swap( expected& lhs, expected& rhs ) noexcept(/*see below*/);
(C++23以降)

std::swap アルゴリズムを std::expected に対してオーバーロードします。lhs と rhs の状態を交換します。実質的に lhs.swap(rhs) を呼び出します。

このオーバーロードは、lhs.swap(rhs) が有効な場合にのみオーバーロード解決に参加します。

この関数は、通常の 修飾なし または 修飾付き名前検索 では可視ではなく、引数依存の名前検索 によってのみ、std::expected<T, E> が引数の関連クラスである場合に発見できます。

パラメータ

lhs, rhs - expected 状態を交換する対象オブジェクト

戻り値

(なし)

例外

noexcept 仕様:
noexcept ( noexcept ( lhs. swap ( rhs ) ) )

例

#include <expected>
#include <iostream>
#include <string_view>
using Ex = std::expected<std::string, int>;
void show(const Ex& ex1, const Ex& ex2, std::string_view term = "\n")
{
    for (int i{}; i != 2; ++i)
    {
        std::cout << (i ? "ex2" : "ex1");
        if (const Ex& ex = (i ? ex2 : ex1); ex.has_value())
            std::cout << ".value() = " << *ex << "  ";
        else
            std::cout << ".error() = " << ex.error() << "  ";
    }
    std::cout << term;
}
int main()
{
    Ex ex1("\N{SMILING FACE WITH SUNGLASSES}");
    Ex ex2{"\N{SLIGHTLY SMILING FACE}"};
    show(ex1, ex2, "after swap(ex1, ex2):\n");
    std::swap(ex1, ex2);
    show(ex1, ex2, "\n\n");
    ex2 = std::unexpected(13);
    show(ex1, ex2, "after swap(ex1, ex2):\n");
    std::swap(ex1, ex2);
    show(ex1, ex2, "\n\n");
    ex2 = std::unexpected(37);
    show(ex1, ex2, "after swap(ex1, ex2):\n");
    std::swap(ex1, ex2);
    show(ex1, ex2);
}

出力:

ex1.value() = 😎  ex2.value() = 🙂  after swap(ex1, ex2):
ex1.value() = 🙂  ex2.value() = 😎  
ex1.value() = 🙂  ex2.error() = 13  after swap(ex1, ex2):
ex1.error() = 13  ex2.value() = 🙂  
ex1.error() = 13  ex2.error() = 37  after swap(ex1, ex2):
ex1.error() = 37  ex2.error() = 13

関連項目

内容を交換する
(公開メンバ関数)