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... の一意な要素でない場合、この呼び出しはill-formedである。

目次

テンプレートパラメータ

I - 検索するインデックス
T - 検索するユニークな型
Types... - variant を構成する型

パラメータ

v - a 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 から実部または虚部への参照を取得する
(関数テンプレート)