Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile-time generate integer sequence with one left out

Answers here and here are pretty much what I need. However, I would like to be able to generate sequences such as:

gen_seq<5, 2> // {0, 1, 3, 4}
gen_seq<3, 0> // {1, 2}
// optional behavior that would be useful for me:
gen_seq<4, 4> // {0, 1, 2, 3}

In the examples I used gen_seq to generate a sequence from 0 to N-1 without I. This is not mandatory, I would also be fine with gen_seq where N is the length of the sequence and I the missing index or other variants.

I think most of the problem is already answered in the linked questions. However I cannot really wrap my head around how to incorporate the "leave this one out" condition for the second parameter.

Ideally, I would love to stick to c++11 features and avoid c++14. Elegant and especially readable soulutions using c++14 could also be very interesting, though.

like image 923
b.buchhold Avatar asked Nov 25 '14 11:11

b.buchhold


1 Answers

You may use the following:

#if 1 // Not in C++11 // make_index_sequence
#include <cstdint>

template <std::size_t...> struct index_sequence {};

template <std::size_t N, std::size_t... Is>
struct make_index_sequence : make_index_sequence<N - 1, N - 1, Is...> {};

template <std::size_t... Is>
struct make_index_sequence<0u, Is...> : index_sequence<Is...> { using type = index_sequence<Is...>; };

#endif // make_index_sequence

namespace detail
{
    template <typename Seq1, std::size_t Offset, typename Seq2> struct concat_seq;

    template <std::size_t ... Is1, std::size_t Offset, std::size_t ... Is2>
    struct concat_seq<index_sequence<Is1...>, Offset, index_sequence<Is2...>>
    {
        using type = index_sequence<Is1..., (Offset + Is2)...>;
    };
}

template <std::size_t N, std::size_t E>
using gen_seq = typename detail::concat_seq<typename make_index_sequence<E>::type, E + 1, typename make_index_sequence<(N > E) ? (N - E - 1) : 0>::type>::type;

static_assert(std::is_same<index_sequence<0, 1, 3, 4>, gen_seq<5, 2>>::value, "");
static_assert(std::is_same<index_sequence<1, 2>, gen_seq<3, 0>>::value, "");
static_assert(std::is_same<index_sequence<0, 1, 2, 3>, gen_seq<4, 4>>::value, "");

Live example

like image 53
Jarod42 Avatar answered Sep 19 '22 10:09

Jarod42