Home > Software design >  C : How to specify types inside a tuple based on types inside another tuple?
C : How to specify types inside a tuple based on types inside another tuple?

Time:04-19

Say I have a tuple type e.g.

using Tuple1 = std::tuple<int, float, double>;

and some templated class

template <typename T>
class DummyClass;

and that I want to specify a tuple type that looks like this

using Tuple2 = std::tuple<DummyClass<std::tuple_element<0, Tuple1>::type>,
                          DummyClass<std::tuple_element<1, Tuple1>::type>,
                          DummyClass<std::tuple_element<2, Tuple1>::type>>;

Only now I'd like to make the above more generic and not have to manually unroll all the types in Tuple2. Is this achievable via template metaprogramming / variadic logic?

CodePudding user response:

Do you mean sth like this?

#include <tuple>
#include <type_traits>


using t1=std::tuple<int,char,float>;

template <typename T>
struct S;

template<typename...Args>
std::tuple<S<Args> ...> maket2(const std::tuple<Args...>&);

template <typename T>
using t2 = decltype(maket2(std::declval<T>()));

static_assert(std::is_same_v<
    t2<t1>, 
    std::tuple<S<int>, S<char>, S<float>>
>);

https://godbolt.org/z/K6KGKzo18 It uses the "classical" meta programming, maybe it can be also achieved using more contemporary constructs.

  • Related