Namespaces
Variants

swap (std::expected)

From cppreference.net
Utilities library
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 ) 가 유효할 때.

이 함수는 일반적인 unqualified 또는 qualified lookup 으로는 보이지 않으며, 인수가 std:: expected < T, E > 의 연관 클래스일 때에만 argument-dependent lookup 에 의해 찾을 수 있습니다.

목차

매개변수

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

참고 항목

내용을 교환합니다
(public member function)