index_sequence
Introduction
The index_sequence
is a compile-time integer sequence to represent indices.
It is employed to facilitate operations on a fixed number of elements, such as accessing a tuple or array.
index_sequence
generates sequences of indices through template recursion and specialization.
It facilitates the generation of an index sequence of a specified length at compile time.
Usage
In addition to the general safety assumptions at the module level which are taken care at the system, the usage guidelines apply for index_sequence.
Usage guidance
estd::index_sequence is used to swaping the elements in tuple. Passing estd::index_sequence as parameter to a function indicates that the implementation is tailored to work with a specific sequence of indices.
Example
The index_sequence generates a sequence of indices.
The following example shows the usage of index_sequence to generate sequence of numbers:
template<typename T>
struct UnpackSequence;
// Defining a structure 'UnpackSequence'.
template<size_t... Index>
struct UnpackSequence<estd::index_sequence<Index...>>
{
size_t values[sizeof...(Index)]{Index...};
};
// make_index_sequence<1> = 0.
EXPECT_THAT(UnpackSequence<estd::make_index_sequence<1>>().values, ElementsAre(0));
// make_index_sequence<3> = 0,1,2.
EXPECT_THAT(UnpackSequence<estd::make_index_sequence<3>>().values, ElementsAre(0, 1, 2));
// make_index_sequence<5> = 0,1,2,3,4.
EXPECT_THAT(UnpackSequence<estd::make_index_sequence<5>>().values, ElementsAre(0, 1, 2, 3, 4));
The following example shows the usage of index_sequence in tuple:
template<class index_sequence>
struct tuple_element_swap_impl;
// Defining a structure 'tuple_element_swap_impl', which used to swap the elements in the tuple
// using selection sort.
template<::size_t... indices>
// Passing '::estd::index_sequence<indices...>' as parameter indicates that this
// implementation is tailored to work with a specific sequence of indices.
struct tuple_element_swap_impl<::estd::index_sequence<indices...>>
{
// Swaps the elements of tuple.
using type = std::tuple<typename std::tuple_element<
(indices != i) && (indices != j) ? indices
: (indices == i) ? j
: i,
Tuple>::type...>;
};