variant_swap2

variant_swap2 (std::variant를 위한 std::swap 오버로드)

이 페이지는 std::variant에 대한 std::swap 알고리즘 오버로드를 설명해요. 이 함수는 두 variant 객체의 값을 교환하며, 내부적으로 lhs.swap(rhs)를 호출해요. C++17부터 사용할 수 있고 C++20부터 constexpr로 동작해요.

출처: cppreference

본문

<variant> 헤더에 정의되어 있어요.

Defined in header <variant>
template < class ... Types > void swap ( std :: variant < Types ... >& lhs, std :: variant < Types ... >& rhs ) noexcept ( /* see below */ ); (since C++17) (constexpr since C++20)

이 함수는 std::variant에 대한 std::swap 알고리즘을 오버로드해요. 실제로는 lhs.swap(rhs)를 호출하는 것과 동일해요.

이 오버로드는 Types... 안의 모든 T_i에 대해 std::is_move_constructible_v<T_i>std::is_swappable_v<T_i>가 모두 true일 때만 오버로드 해석에 참여해요.

매개변수 (Parameters)

| lhs, rhs | - | 값을 교환할 variant 객체 |

반환값 (Return value)

없음

예외 (Exceptions)

  • noexcept(noexcept(lhs.swap(rhs)))

참고 (Notes)

Feature-test macro Value Std Feature
__cpp_lib_variant 202106L (C++20) (DR) Fully constexpr std::variant

예제 (Example)

#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

결함 보고서 (Defect reports)

다음 동작 변경 결함 보고서는 이전에 발표된 C++ 표준에 소급 적용되었어요.

DR Applied to Behavior as published Correct behavior
P2231R1 C++20 swap was not constexpr while the required operations can be constexpr in C++20 made constexpr

같이 보기 (See also)

swap swaps with another variant (public member function) [edit]

더 알아보기 (Learn more)

cppreference