Get type of a std::variant member at a given index during compile time
Asked Answered
D

2

6

I have defined the following variant:

std::variant<int, bool, MyType, int> myVar;

The type of the member at index 2 is MyType. How to get this during compile time? (so that I can use it in a constexpr context etc..)

Debacle answered 27/7, 2020 at 19:18 Comment(0)
Y
10

Use std::variant_alternative

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.

using T = std::variant_alternative_t<2, decltype(myVar)>;
Yahoo answered 27/7, 2020 at 19:21 Comment(0)
A
8

Since C++17, you can use std::variant_alternative_t

std::variant_alternative_t<0, std::variant<int, std::string>> i; // int
std::variant_alternative_t<1, std::variant<int, std::string>> s; // string
Allo answered 27/7, 2020 at 19:21 Comment(2)
Thanks for the answer. Shouldn't we swap the template typenames. i.e. index goes first ?Debacle
@Sumudu yup. fixedAllo

© 2022 - 2024 — McMap. All rights reserved.