Type function returning a tuple of selected types

I implemented a function of type Tuple , which turns the list of My_enum values ​​into std::tuple corresponding types:

 #include <tuple> enum My_enum{ t_int, t_double }; // Bind_type is a type function that given a My_enum returns the corresponding type template<My_enum E> struct Bind_type; template<> struct Bind_type<t_int>{ using type = int; }; template<> struct Bind_type<t_double>{ using type = double; }; // Tuple is a type function that given a template value parameter pack of My_enums returns a std::tuple of correspondig types template<My_enum First, My_enum... Others> struct Tuple { using type = decltype(std::tuple_cat( typename Tuple<First>::type{}, typename Tuple<Others...>::type{} )); }; template<> struct Tuple<t_int> { using type = std::tuple<Bind_type<t_int>::type>; }; template<> struct Tuple<t_double> { using type = std::tuple<Bind_type<t_double>::type>; }; 

I would like to declare a base recursion case for Tuple one shot because I don't want to manually control the Tuple specialization while I add or remove values ​​before My_enum , because it is error prone (and boring). I tried:

 template<My_enum E> struct Tuple { using type = std::tuple<Bind_type<E>::type>; }; 

but this is not a valid specialization for the variation version.

My question is: is there a smart way to declare a Tuple specialization when it has only one template value parameter?

+5
source share
1 answer

You can do this without recursion by simply expanding the options package directly in std::tuple :

 template<My_enum... Enums> struct Tuple { using type = std::tuple<typename Bind_type<Enums>::type...>; }; 

To more accurately answer your question, you can declare a variable primary template, and then write two specializations: if there are at least two parameters, and when there is only one:

 //primary template, takes any number of My_enums template <My_enum... Enums> struct Tuple { //this case will be chosen if we instantiate a Tuple with no args using type = std::tuple<>; } //specialization for when there are at least two arguments template<My_enum First, My_enum Second, My_enum... Others> struct Tuple<First,Second,Others...> { using type = decltype(std::tuple_cat( typename Tuple<First>::type{}, typename Tuple<Second,Others...>::type{} )); }; //base case, only one argument left template<My_enum Last> struct Tuple<Last> { using type = std::tuple<typename Bind_type<Last>::type>; }; 
+6
source

All Articles