Variadic模板类,从其参数列表中获取特定类型的索引

时间:2014-12-21 09:33:12

标签: c++ class variadic-templates

是否可以实现可变参数模板类的函数成员,该函数成员从可变参数列表返回给定类型的索引。

我看到的问题是创建某种假的可变参数列表,只是为了触发编译时模板评估。

template<typename... TArgs>
class Foo
{
  template<typename T, typename TArg>
  int _get_idx(int i, const TArg &curr, TArgs...args)
  {
    if (std::is_same(T, TArg)) {
        return i;
    }
    else {
        return get_id(i+1, args...);
    }
  }

用法如下:

Foo<A, B, C> foo;
int i = foo.get_idx<B>(); // i == 1

1 个答案:

答案 0 :(得分:6)

您可以使用以下内容:

template <typename T, typename... Ts> struct get_index;

template <typename T, typename... Ts>
struct get_index<T, T, Ts...> : std::integral_constant<std::size_t, 0> {};

template <typename T, typename Tail, typename... Ts>
struct get_index<T, Tail, Ts...> :
    std::integral_constant<std::size_t, 1 + get_index<T, Ts...>::value> {};

#if 1 // explicit error case, but you already have error without that. 
template <typename T>
struct get_index<T>
{
    // condition is always false, but should be dependant of T
    static_assert(sizeof(T) == 0, "element not found");
};
#endif

Live example

注意:您没有指定重复匹配类型会发生什么(所以我选择第一个), 也不是类型不匹配(所以我做了编译时错误)

Live Demo with duplicates