variant_get_if
variant_get_if (variant 값 포인터 얻기)
std::get_if 함수 템플릿은 std::variant 객체에 저장된 값을 가리키는 포인터를 반환해요. 인덱스나 타입으로 원하는 값을 조회할 수 있고, 실패하면 널 포인터를 돌려줘요. 예외를 던지는 std::get과 달리 오류를 안전하게 처리할 수 있어요.
출처: cppreference
본문
<variant> 헤더에 정의되어 있어요. 오버로드 (1)과 (2)는 인덱스 I로 값을 조회하고, 오버로드 (3)과 (4)는 타입 T로 값을 조회해요. 타입으로 조회할 때는 Types... 중에서 T가 유일해야 해요. const std::variant에 대해서는 const 포인터를 반환해요.
| Defined in header |
||
|---|---|---|
| template < std :: size_t I , class ... Types > constexpr std :: add_pointer_t < std :: variant_alternative_t < I , std :: variant < Types ... >>> get_if ( std :: variant < Types ... >* pv ) noexcept ; | (1) | (since C++17) |
| template < std :: size_t I , class ... Types > constexpr std :: add_pointer_t < const std :: variant_alternative_t < I , std :: variant < Types ... >>> get_if ( const std :: variant < Types ... >* pv ) noexcept ; | (2) | (since C++17) |
| template < class T , class ... Types > constexpr std :: add_pointer_t < T > get_if ( std :: variant < Types ... >* pv ) noexcept ; | (3) | (since C++17) |
| template < class T , class ... Types > constexpr std :: add_pointer_t < const T > get_if ( const std :: variant < Types ... >* pv ) noexcept ; | (4) | (since C++17) |
템플릿 매개변수
| I | - | 조회할 인덱스예요 |
|---|---|---|
| Type | - | 조회할 고유 타입이에요 |
매개변수
| pv | - | variant를 가리키는 포인터예요 |
|---|
반환값
가리키는 variant에 저장된 값을 가리키는 포인터를 반환해요. 오류가 있으면 널 포인터를 반환해요.
예제
#include <iostream>
#include <variant>
int main()
{
auto check_value = [](const std::variant<int, float>& v)
{
if (const int* pval = std::get_if<int>(&v))
std::cout << "variant value: " << *pval << '\n';
else
std::cout << "failed to get value!" << '\n';
};
std::variant<int, float> v{12}, w{3.f};
check_value(v);
check_value(w);
}
출력:
variant value: 12
failed to get value!
같이 보기
| get (std::variant) (C++17) | 인덱스나 타입으로 variant의 값을 읽어요. 타입이 유일해야 하며, 오류가 있으면 예외를 던져요 (함수 템플릿) [편집] |
|---|