6

Who knows how to implement C++ std::make_index_sequence reverse version. To get - make_index_sequence_reverse<int, 5> = <4,3,2,1,0>. Thank you!

2
  • Welcome to SO! Please take a look at how to ask questions .- can you post any attempts you've made? Commented Jul 18, 2018 at 19:02
  • @Andrey Avraliov Also accept an answer! Commented May 31, 2022 at 5:52

2 Answers 2

12

IMHO, there is no reason for a index_sequence_reverse: std::index_sequence support sequences of indexes and are order neutral (or even without order).

If you can use std::make_index_sequence, for a makeIndexSequenceReverse you can make something as follows

#include <utility>
#include <type_traits>

template <std::size_t ... Is>
constexpr auto indexSequenceReverse (std::index_sequence<Is...> const &)
   -> decltype( std::index_sequence<sizeof...(Is)-1U-Is...>{} );

template <std::size_t N>
using makeIndexSequenceReverse
   = decltype(indexSequenceReverse(std::make_index_sequence<N>{}));

int main ()
 {
   static_assert( std::is_same<std::index_sequence<4U, 3U, 2U, 1U, 0U>,
      makeIndexSequenceReverse<5U>>::value, "!" );
 }
Sign up to request clarification or add additional context in comments.

1 Comment

This was not the OP's question, but I would like to note something here: Inverting a sequence with sizeof...(Is)-1u-Is only works if the index sequence covers the full range of the original type sequence (e.g., from a tuple). If the index sequence is only a subset, one must consider the size of the original type sequence and the base index of the subset.
2

Here's a way to do it with inheritance:

template <std::size_t, typename>
struct make_reverse_index_sequence_helper;

template <std::size_t N, std::size_t...NN>
struct make_reverse_index_sequence_helper<N, std::index_sequence<NN...>> 
   : std::index_sequence<(N - NN)...> {};

template <size_t N>
struct make_reverse_index_sequence 
   : make_reverse_index_sequence_helper<N - 1, 
        decltype(std::make_index_sequence<N>{})> {};

The helper struct is used to deduce the parameters and apply the subtraction. It can be used just like std::make_index_sequence because it derives from std::index_sequence, as you can see here:

std::index_sequence<4, 3, 2, 1, 0> x = make_reverse_index_sequence<5>{};

1 Comment

This solution is general and consistent with the STL, much appreciated!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.