Convert std::variant to std::tuple of template class instances

Viewed 103

transform_v2t function in the code below builds a tuple of template class A instances:

template <typename T>
struct A
{
    T val;
};

template <class V, template <class> class T, std::size_t... index>
inline constexpr auto transform_v2t(std::index_sequence<index...>)
{
    return std::make_tuple(T<std::variant_alternative_t<index, V>>() ...);
}

template <class V, template <class> class T>
inline constexpr auto transform_v2t()
{
    return transform_v2t<V, T>(std::make_index_sequence<std::variant_size_v<V>>());
}

typedef std::variant<bool, char, int, float, double, std::string> V;

int main()
{
    auto t1 = transform_v2t<V, A>();
}

is it possible to apply the same transform_v2t function to a class with two template arguments, for example:

template <typename P, typename T>
struct B
{
    P other_val;
    T val;
};

with P specialized as int?

with a pseudo code it can be something like this:

template <class T> typedef B<int, T> PartiallySpecializedB;
auto t2 = transform_v2t<V, PartiallySpecializedB>();

see online sample code.

1 Answers

Never use typedef in post-C++11 code, always prefer using (known as alias declarations).

Not only are they easier to read because the name you're declaring is on the left (as opposed to... wherever):

using V = std::variant<bool, char, int, float, double, std::string>;

... but they also have support for alias template declarations:

template <class T> 
using PartiallySpecializedB = B<int, T>;

auto t2 = transform_v2t<V, PartiallySpecializedB>();
Related