Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Nth type of variadic template templates?

How to get the Nth type of variadic template templates? For example

template<typename... Args>
class MyClass
{
    Args[0] mA; // This is wrong. How to get the type?

};
like image 538
user1899020 Avatar asked Apr 11 '13 15:04

user1899020


2 Answers

You can use std::tuple:

#include<tuple>

template<typename... Args>
class MyClass
{
    typename std::tuple_element<0, std::tuple<Args...> >::type mA;
};
like image 177
zch Avatar answered Nov 15 '22 18:11

zch


If you want something without using std::tuple this works

template<std::size_t N, typename T, typename... types>
struct get_Nth_type
{
    using type = typename get_Nth_type<N - 1, types...>::type;
};

template<typename T, typename... types>
struct get_Nth_type<0, T, types...>
{
    using type = T;
};

Than

template<std::size_t N, typename... Args>
using get = typename get_Nth_type<N, Args...>::type;

template<typename... Args>
class MyClass
{
    get<0, Args...> mA;
};
like image 43
etrusks Avatar answered Nov 15 '22 19:11

etrusks