Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++17

variant

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..)

like image 436
Anubis Avatar asked Jul 27 '20 19:07

Anubis


Video Answer


2 Answers

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)>;
like image 51
StoryTeller - Unslander Monica Avatar answered Nov 15 '22 04:11

StoryTeller - Unslander Monica


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
like image 40
user253751 Avatar answered Nov 15 '22 04:11

user253751