如何在可变类型包中获取类型的索引

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

本文关键字:包中获 取类型 索引 类型      更新时间:2023-10-16

例如

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

假设T是Ts中的一个,并且Ts有不同的类型,比如

Index<int, int, double>::value is 0
Index<double, int, double>::value is 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> {};

您可能想要添加一个c++14变量模板:

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

DEMO