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

谁都会走 提交于 2019-12-07 04:49:43

问题


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

回答1:


#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-fashion variable template:

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

DEMO



来源:https://stackoverflow.com/questions/26169198/how-to-get-the-index-of-a-type-in-a-variadic-type-pack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!