Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an element of type list by index

How can an element of a type list using L = type_list<T1, T2, ...> be retrieved by index, like std::tuple_element, preferrably in a non recursive way?

I want to avoid using tuples as type lists for use cases, that require instantiation for passing a list like f(L{}).

template<typename...> struct type_list {};
using L = typelist<int, char, float, double>;
using T = typeAt<2, L>; // possible use case

Not sure if an iteration using std::index_sequence and a test via std::is_same of the std::integral_constant version of the index is a good aproach.

like image 389
Chris G. Avatar asked Sep 18 '25 20:09

Chris G.


2 Answers

I want to avoid using tuples as type lists for use cases, that require instantiation for passing a list like f(L{})

If you don't want to instanciate std::tuple but you're ok with it in unevaluated contexts, you may take advantage of std::tuple_element to implement your typeAt trait:

template <std::size_t I, typename T>
struct typeAt;

template <std::size_t I, typename... Args>
struct typeAt<I, type_list<Args...>> : std::tuple_element<I, std::tuple<Args...>> {};
                                    // ^ let library authors do the work for you

using L = type_list<int, char, float, double>;
using T = typename typeAt<2, L>::type;

static_assert(std::is_same<T, float>::value, "");
like image 93
paolo Avatar answered Sep 20 '25 11:09

paolo


Using Boost.Mp11, this is a one-liner (as always):

template<typename...> struct type_list {};
using L = typelist<int, char, float, double>;
using T = mp_at_c<L, 2>; // <==

Note that this will compile significantly more efficiently than using tuple_element. On clang, the implementation even uses a compiler intrinsic.

like image 43
Barry Avatar answered Sep 20 '25 10:09

Barry