std::variant_alternative, std::variant_alternative_t

Header: <variant>

Provides compile-time indexed access to the types of the alternatives of the possibly cv-qualified variant, combining cv-qualifications of the variant (if any) with the cv-qualifications of the alternative.

# Declarations

template <std::size_t I, class T>
struct variant_alternative; /* undefined */

(since C++17)

template <std::size_t I, class... Types>
struct variant_alternative<I, variant<Types...>>;

(since C++17)

template <std::size_t I, class T> class variant_alternative<I, const T>;

(since C++17)

template <std::size_t I, class T>
class variant_alternative<I, volatile T>;
template <std::size_t I, class T>
class variant_alternative<I, const volatile T>;

(since C++17) (deprecated in C++20)

# Example

#include <variant>
#include <iostream>
 
using my_variant = std::variant<int, float>;
static_assert(std::is_same_v
    <int,   std::variant_alternative_t<0, my_variant>>);
static_assert(std::is_same_v
    <float, std::variant_alternative_t<1, my_variant>>);
// cv-qualification on the variant type propagates to the extracted alternative type.
static_assert(std::is_same_v
    <const int, std::variant_alternative_t<0, const my_variant>>);
 
int main()
{
    std::cout << "All static assertions passed.\n";
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 2974C++17out-of-bounds index resulted in undefined behaviormade ill-formed

# See also