Namespaces
Variants

std:: get (std::variant)

From cppreference.net
Utilities library
(원문에 번역할 텍스트가 없으므로 동일한 HTML 구조를 유지합니다)
헤더 파일에 정의됨 <variant>
(1) (C++17 이후)
template < std:: size_t I, class ... Types >

constexpr std:: variant_alternative_t < I, std:: variant < Types... >> &

get ( std:: variant < Types... > & v ) ;
template < std:: size_t I, class ... Types >

constexpr std:: variant_alternative_t < I, std:: variant < Types... >> &&

get ( std:: variant < Types... > && v ) ;
template < std:: size_t I, class ... Types >

constexpr const std:: variant_alternative_t < I, std:: variant < Types... >> &

get ( const std:: variant < Types... > & v ) ;
template < std:: size_t I, class ... Types >

constexpr const std:: variant_alternative_t < I, std:: variant < Types... >> &&

get ( const std:: variant < Types... > && v ) ;
(2) (C++17부터)
template < class T, class ... Types >
constexpr T & get ( std:: variant < Types... > & v ) ;
template < class T, class ... Types >
constexpr T && get ( std:: variant < Types... > && v ) ;
template < class T, class ... Types >
constexpr const T & get ( const std:: variant < Types... > & v ) ;
template < class T, class ... Types >
constexpr const T && get ( const std:: variant < Types... > && v ) ;
1) 인덱스 기반 값 접근자: 만약 v. index ( ) == I 이면, v 에 저장된 값에 대한 참조를 반환합니다. 그렇지 않으면 std::bad_variant_access 를 던집니다. I 가 variant에서 유효한 인덱스가 아닌 경우 이 호출은 ill-formed입니다.
2) 타입 기반 값 접근자: 만약 v 가 대체 타입 T 를 보유하고 있다면, v 에 저장된 값에 대한 참조를 반환합니다. 그렇지 않으면 std::bad_variant_access 를 발생시킵니다. T Types... 의 고유한 요소가 아닌 경우 이 호출은 잘못된 형식입니다.

목차

템플릿 매개변수

I - 조회할 인덱스
T - 조회할 고유 타입
Types... - variant 을 구성하는 타입들

매개변수

v - a variant

반환값

variant에 저장된 값에 대한 참조입니다.

예외

1,2) 오류 발생 시 std::bad_variant_access 를 발생시킵니다.

예제

#include <iostream>
#include <string>
#include <variant>
int main()
{
    std::variant<int, float> v{12}, w;
    std::cout << std::get<int>(v) << '\n';
    w = std::get<int>(v);
    w = std::get<0>(v); // 이전 줄과 동일한 효과
//  std::get<double>(v); // 오류: [int, float]에 double 없음
//  std::get<3>(v);      // 오류: 유효한 인덱스 값은 0과 1
    try
    {
        w = 42.0f;
        std::cout << std::get<float>(w) << '\n'; // ok, 42 출력
        w = 42;
        std::cout << std::get<float>(w) << '\n'; // 예외 발생
    }
    catch (std::bad_variant_access const& ex)
    {
        std::cout << ex.what() << ": w에 float가 아닌 int가 포함됨\n";
    }
}

가능한 출력:

12
42
Unexpected index: w contained int, not float

참고 항목

(C++17)
인덱스나 타입(고유한 경우)이 주어지면 가리키는 variant 값에 대한 포인터를 얻으며, 오류 시 null을 반환함
(함수 템플릿)
튜플의 지정된 요소에 접근함
(함수 템플릿)
array 의 요소에 접근함
(함수 템플릿)
pair 의 요소에 접근함
(함수 템플릿)
std::ranges::subrange 에서 반복자나 센티널을 얻음
(함수 템플릿)
std::complex 에서 실수부나 허수부에 대한 참조를 얻음
(함수 템플릿)