Jes Jes - 21 days ago 6
C++ Question

Implement C++ template for generating an index sequence with a given range

So, C++14 provides struct

make_index_sequence<N>
for generating an index sequence from
0
to
N-1
. I am wondering how to implement one to generate an index sequence in a given range. For example:

template <size_t Min, size_t Max>
struct make_index_range;

// make_index_range<5, 9> will give index_sequence<5, 6, 7, 8>

Answer

The way you defined index_range (before the question was edited) the answer is simply:

template<std::size_t Min, std::size_t Max>
  using make_index_range = index_range<Min, Max>;

Which is not very useful.

So I'm going to assume you mean make_index_range<5, 9> will give index_sequence<5, 6, 7, 8>, which can be done like this:

#include <utility>

template<std::size_t N, std::size_t... Seq>
  constexpr std::index_sequence<N + Seq ...>
  add(std::index_sequence<Seq...>)
  { return {}; }

template<std::size_t Min, std::size_t Max>
  using make_index_range = decltype(add<Min>(make_index_sequence<Max-Min>()));

Or if you want make_index_range to be a class template, define add as above and then:

template<std::size_t Min, std::size_t Max>
  struct make_index_range {
    using type = decltype(add<Min>(make_index_sequence<Max-Min>()));
  };

(But with this you have to use make_index_range<5, 9>::type so the alias template is probably better, and closer to how make_index_sequence works.)