Search code examples
c++variadic-templatestemplate-meta-programming

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>
{
};

Solution

  • You get the error because

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

    is undefined. It should be

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

    instead.