【问题标题】:How to get the index of a type in a variadic type pack?如何获取可变参数类型包中类型的索引?
【发布时间】:2014-11-27 22:28:38
【问题描述】:
例如
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
【问题讨论】:
标签:
c++
c++11
variadic-templates
【解决方案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