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!
c++ reversed integer sequence implementation
Asked Answered
Welcome to SO! Please take a look at how to ask questions .- can you post any attempts you've made? –
Greenbrier
@Andrey Avraliov Also accept an answer! –
Frayne
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, "!" );
}
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. –
Frayne 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>{};
This solution is general and consistent with the STL, much appreciated! –
Perkin
© 2022 - 2024 — McMap. All rights reserved.