C++ variadic templates: elegant way of listing all array elements depending on variadic template size

Viewed 48

Is there some elegant way to express a function call depending on some n which can be derived from template arguments

f(my_array[0], ... , my_array[n-1]);

inside a class template looking like this?:

template <int... numbers>
class Abraham {
   static constexpr std::size_t n = sizeof...(numbers);
   some_type my_array[n];

   void foo(){
   //...
   f(my_array[0], ... , my_array[n-1]); // This line is no valid C++ Code. How can one achieve this in an elegant way?
   //...
   }
}
1 Answers

The standard library has std::index_sequence for this kind of thing

template <size_t... Is>
void foo(std::index_sequence<Is...>) {
  f(my_array[Is]...);
}
void foo() {
  foo(std::make_index_sequence<n>{});
}

Demo: https://godbolt.org/z/zhbGdb

Related