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

Variadic template class, getting index of a specific type from its argument list

本文关键字:参数 获取 类型 索引 列表 变参      更新时间:2023-10-16

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

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

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

你可以使用这样的东西:

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

现场示例

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

带有重复项的现场演示