Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Index of a type in a Typelist

I have a simple TypeList implimentation, like this:

template<typename... Ts>
struct TypeList
{
    static constexpr std::size_t size{ sizeof... (Ts) };
};

struct T1
    {
    };

struct T2
        {
        };

struct T3
        {
        };

using Types = mpl::TypeList<T1, T2, T3>;

I want to figure out the index of the type T2 inside of the typelist Types. This is what I am currently using, however it only works if the type I am searching for is at the beginning of the typelist. Otherwise, it compiles with the error "value: undeclared identifier".

template<typename, typename>
struct IndexOf {};

// IndexOf base case: found the type we're looking for.
template <typename T, typename... Ts>
struct IndexOf<T, TypeList<T, Ts...>>
    : std::integral_constant<std::size_t, 0>
{
};



// IndexOf recursive case: 1 + IndexOf the rest of the types.
template <typename T, typename TOther, typename... Ts>
struct IndexOf<T, TypeList<TOther, Ts...>>
    : std::integral_constant<std::size_t,
    1 + IndexOf<T, Ts...>::value>
{
};
like image 212
Acorn Avatar asked Jan 10 '17 22:01

Acorn


1 Answers

You get the error because

IndeOf<T, Ts...>::value

is undefined. It should be

IndexOf<T, TypeList<Ts...>>::value

instead.

like image 82
jbab Avatar answered Oct 20 '22 04:10

jbab