This question is a follow-up. The original question was itself a follow-up to an older question by @LokiAstari.
The idea is to provide a compile-time integer range.
This version incorporates almost everything from the answers and comments to the previous iteration of the review (except the handling of corner cases such as INT_MAX
, which is kind of hard). Along with the fixes comes a new feature: the possibility to specify the « step » of the range. Here is the new implementation:
#include <cstddef>
#include <utility>
namespace detail
{
template<
typename Integer,
typename SequenceBase,
Integer Begin,
Integer Step,
bool IsIncreasing
>
struct integer_range_impl;
template<
typename Integer,
Integer... N,
Integer Begin,
Integer Step
>
struct integer_range_impl<Integer, std::integer_sequence<Integer, N...>, Begin, Step, true>
{
using type = std::integer_sequence<Integer, (N * Step + Begin)...>;
};
template<
typename Integer,
Integer... N,
Integer Begin,
Integer Step
>
struct integer_range_impl<Integer, std::integer_sequence<Integer, N...>, Begin, Step, false>
{
using type = std::integer_sequence<Integer, (Begin - N * Step)...>;
};
}
template<
typename Integer,
Integer Begin,
Integer End,
Integer Step
>
using make_integer_range = typename detail::integer_range_impl<
Integer,
std::make_integer_sequence<
Integer,
((Begin < End ? End - Begin : Begin - End) - 1) / Step + 1
>,
Begin,
Step,
(Begin < End)
>::type;
template<std::size_t Begin, std::size_t End, std::size_t Step>
using make_index_range = make_integer_range<std::size_t, Begin, End, Step>;
Here is an example of how this template integer range can be used:
#include <array>
#include <iostream>
#include <iterator>
#include <numeric>
template<typename T, std::size_t N, std::size_t... Ind>
auto print(const std::array<T, N>& arr, std::index_sequence<Ind...>)
-> void
{
int dummy[] = {
(std::cout << std::get<Ind>(arr) << ' ', 0)...
};
(void) dummy;
}
int main()
{
std::array<int, 20u> arr;
std::iota(std::begin(arr), std::end(arr), 0);
// prints 15 12 9 6 3
print(arr, make_index_range<15u, 0u, 3u>{});
}
I accept any kind of review, be it about style, correctness or possible improvements to the utility in general :)