2014-10-02 26 views
5

例如如何获得可变类型包中某个类型的索引?

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 
+6

这几乎是你去年的问题的重复:[获取元组元素类型的索引?](http://stackoverflow.com/q/18063451) – dyp 2014-10-02 20:48:54

+0

@dyp(问一个关于variardics的问题,+ +年)''... – Yakk 2014-10-03 13:47:19

回答

12
#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

相关问题