Variadic class template that receives an index of a specific type from an argument list

Is it possible to implement a member of a function of a variational class of a template that returns an index of a given type from a list of variational arguments.

The problem I see is creating some sort of fake variational argument list, just to start compiling the compile-time pattern.

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...);
    }
  }

Usage will be something like this:

Foo<A, B, C> foo;
int i = foo.get_idx<B>(); // i == 1
+4
source share
1 answer

You can use something like:

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

Living example

Note. You do not indicate what happens for the type of duplicate match (so I take the first one), or if the type is not mapped (so I made a compile-time error)

Live Demo

+6

Source: https://habr.com/ru/post/1568510/


All Articles