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!
Asked
Active
Viewed 1,528 times
4

max66
- 65,235
- 10
- 71
- 111

Andrey Avraliov
- 61
- 3
-
Welcome to SO! Please take a look at [how to ask](https://stackoverflow.com/help/how-to-ask) questions .- can you post any attempts you've made? – R Balasubramanian Jul 18 '18 at 19:02
-
@Andrey Avraliov Also accept an answer! – klaus triendl May 31 '22 at 05:52
2 Answers
10
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, "!" );
}

max66
- 65,235
- 10
- 71
- 111
-
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. – klaus triendl May 31 '22 at 08:15
1
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>{};

Eightfold
- 41
- 2
-
This solution is general and consistent with the STL, much appreciated! – okovko Feb 03 '23 at 06:53