Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the index of a type in a variadic type pack?

For example

template<typename T, typename... Ts>
struct Index
{
    enum {value = ???}
};

and assume T is one of Ts and Ts has different types, like

Index<int, int, double>::value is 0
Index<double, int, double>::value is 1
like image 570
user1899020 Avatar asked Oct 02 '14 20:10

user1899020


1 Answers

#include <type_traits>
#include <cstddef>

template <typename T, typename... Ts>
struct Index;

template <typename T, typename... Ts>
struct Index<T, T, Ts...> : std::integral_constant<std::size_t, 0> {};

template <typename T, typename U, typename... Ts>
struct Index<T, U, Ts...> : std::integral_constant<std::size_t, 1 + Index<T, Ts...>::value> {};

You might like to add a c++14 variable template:

template <typename T, typename... Ts>
constexpr std::size_t Index_v = Index<T, Ts...>::value;

DEMO

like image 85
Piotr Skotnicki Avatar answered Oct 15 '22 13:10

Piotr Skotnicki