Get std::variant types at compile time

Viewed 546

Suppose we have defined somewhere:

using mytype_t = std::variant<int, float>;

I want to retrieve all possible types that coud be stored by mytype_t. I have checked the reference. There is no member types defined that I can use (something like: mytype_t::value_types).

I am trying to do something like this:

using myvectype_t = std::variant<std::vector<mytype_t::value_types>...>;
1 Answers

You do not need a special member for that, because the information is all right there in the type:

#include <variant>
#include <iostream>
#include <vector>
#include <type_traits>

template <typename T>
struct foo;

template <typename...V>
struct foo< std::variant<V...>> {
    using type = std::variant<  std::vector<V> ...>;
};


int main() {
    using vari = std::variant<int,double>;
    using varivect = std::variant< std::vector<int>, std::vector<double>>;
    std::cout << std::is_same<foo<vari>::type,varivect>::value;
}

Output:

1

Live example

Related