Namespaces
Variants

std:: get_if (std::variant)

From cppreference.net
Utilities library
定義先ヘッダ <variant>
(1) (C++17以降)
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 ;
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) (C++17以降)
template < class T, class ... Types >

constexpr std:: add_pointer_t < T >

get_if ( std:: variant < Types... > * pv ) noexcept ;
template < class T, class ... Types >

constexpr std:: add_pointer_t < const T >

get_if ( const std:: variant < Types... > * pv ) noexcept ;
1) インデックスベースの非スローアクセサ: pv がnullポインタでなく、かつ pv - > index ( ) == I の場合、 pv が指すvariantに格納されている値へのポインタを返す。それ以外の場合、nullポインタ値を返す。 I がvariantの有効なインデックスでない場合、この呼び出しはill-formedである。
2) 型ベースの非スローアクセサ: (1) と同等で、 I Types... 内の T の0ベースのインデックスです。 T Types... の一意な要素でない場合、この呼び出しはill-formedです。

目次

テンプレートパラメータ

I - 検索するインデックス
Type - 検索するユニーク型

パラメータ

pv - バリアントへのポインタ

戻り値

指されたvariantに格納されている値へのポインタ、またはエラー時のnullポインタ。

#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!

関連項目

インデックスまたは型(型が一意の場合)を指定してvariantの値を読み取り、エラー時には例外をスローする
(関数テンプレート)