Namespaces
Variants

std:: bad_variant_access

From cppreference.net
Utilities library
ヘッダーで定義 <variant>
class bad_variant_access : public std:: exception
(C++17以降)

std::bad_variant_access は以下の状況でスローされる例外の型です:

(C++26以降)

std::bad_variant_access の全メンバ関数は constexpr です:定数式の評価中に std::bad_variant_access オブジェクトを作成して使用することが可能です。

ただし、 std::bad_variant_access オブジェクトは一般に constexpr にはなりません。なぜなら、動的に確保されたストレージはすべて同じ定数式の評価中に解放されなければならないためです。

(C++26以降)

目次

メンバー関数

(constructor)
新しい bad_variant_access オブジェクトを構築する
(public member function)
operator=
bad_variant_access オブジェクトを置き換える
(public member function)
what
説明文字列を返す
(public member function)

std::bad_variant_access:: bad_variant_access

bad_variant_access ( ) noexcept ;
(1) (C++17以降)
(constexpr since C++26)
bad_variant_access ( const bad_variant_access & other ) noexcept ;
(2) (C++17以降)
(constexpr since C++26)

新しい bad_variant_access オブジェクトを構築します。実装定義のnull終端バイト文字列が含まれており、 what() を通じてアクセス可能です。

1) デフォルトコンストラクタ。
2) コピーコンストラクタ。 * this other の両方が動的型 std::bad_variant_access を持つ場合、 std:: strcmp ( what ( ) , other. what ( ) ) == 0 となります。

パラメータ

other - コピーする別の例外オブジェクト

std::bad_variant_access:: operator=

bad_variant_access & operator = ( const bad_variant_access & other ) noexcept ;
(C++17以降)
(constexpr C++26以降)

other の内容を代入します。 * this other の両方が動的型 std::bad_variant_access を持つ場合、代入後は std:: strcmp ( what ( ) , other. what ( ) ) == 0 となります。

パラメータ

other - 代入する別の例外オブジェクト

戻り値

* this

std::bad_variant_access:: what

virtual const char * what ( ) const noexcept ;
(C++17以降)
(constexpr C++26以降)

説明文字列を返します。

戻り値

説明情報を含む実装定義のナル終端文字列へのポインタ。この文字列は std::wstring への変換と表示に適しています。ポインタは、少なくとも取得元の例外オブジェクトが破棄されるまで、または例外オブジェクトの非constメンバ関数(コピー代入演算子など)が呼び出されるまで有効であることが保証されます。

定数評価中、返される文字列は通常のリテラルエンコーディングでエンコードされます。

(C++26以降)

注記

実装は what() をオーバーライドすることが許可されていますが、必須ではありません。

std::exception から継承 std:: exception

メンバ関数

例外オブジェクトを破棄
( std::exception の仮想公開メンバ関数)
[virtual]
説明文字列を返す
( std::exception の仮想公開メンバ関数)

注記

機能テスト マクロ 標準 機能
__cpp_lib_constexpr_exceptions 202502L (C++26) constexpr std::bad_variant_access

#include <iostream>
#include <variant>
int main()
{
    std::variant<int, float> v;
    v = 12;
    try
    {
        std::get<float>(v);
    }
    catch (const std::bad_variant_access& e)
    {
        std::cout << e.what() << '\n';
    }
}

出力例:

bad_variant_access

関連項目

インデックスまたは型(型が一意の場合)を指定してvariantの値を読み取り、エラー時に例外をスローする
(関数テンプレート)
(C++17)
1つ以上の variant が保持する引数で指定された関数オブジェクトを呼び出す
(関数テンプレート)
(C++26)
variant が保持する引数で指定された関数オブジェクトを呼び出す
(公開メンバ関数)
値を含まないoptionalへのチェック付きアクセスを示す例外
(クラス)
予期しない値を含む expected へのチェック付きアクセスを示す例外
(クラステンプレート)