在编译期间获取给定索引处的 std::variant 成员的类型

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

我定义了以下变体:

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

索引 2 处的成员类型是 MyType。如何在编译时得到这个? (以便我可以在 constexpr 上下文等中使用它。)

使用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)>;

自 C++17 起,您可以使用 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