I have this code that generates an compile-time array of 1 to 10
template <int... Is> // when called below, Is will be 0 - N
constexpr std::array<int, sizeof...(Is)>
make_inc_array_impl(std::integer_sequence<int, Is...>) {
return {{(Is + 1)...}}; // +1 to start at one instead of [0, 1, ...]
}
template <std::size_t N>
constexpr std::array<int, N> make_inc_array() {
return make_inc_array_impl(std::make_integer_sequence<int, N>{});
}
constexpr auto a = make_inc_array<10>(); // [1, 2, ..., 10]
int main() {
for(int itr = 0; itr < 10; ++itr)
printf("%d ", a[itr]);
}
Well, I've got some experience and knowledge of how meta-programming works. But still I don't get how this amazing example really works.
From the
make_inc_array_impl()
, I see that, it returns(Is+1)...
So should the result be[11, 10, 9, 8, 7, ... 2]
sinceIs
value starts from10
?How is the variadic template function
make_integer_sequence(parameter pack)
unfolds/expands thestd::integer_sequence<int, Is...>
? In a normal meta-programming, template deduction works recursively fromN
toN-1
, down to1
. But here why it results from1
toN
?
Could you help to explain what the principle behind?