Hello i'm learning C++11, I'm wondering how to make a constexpr 0 to n array, for example:
n = 5;
int array[] = {0 ... n};
so array may be {0, 1, 2, 3, 4, 5}
Hello i'm learning C++11, I'm wondering how to make a constexpr 0 to n array, for example:
n = 5;
int array[] = {0 ... n};
so array may be {0, 1, 2, 3, 4, 5}
Based on @Xeo's excellent idea, here is an approach that lets you fill an array of
constexpr std::array<T, N> a = { fun(0), fun(1), ..., fun(N-1) };
T
is any literal type (not justint
or other valid non-type template parameter types), but alsodouble
, orstd::complex
(from C++14 onward)fun()
is anyconstexpr
functionstd::make_integer_sequence
from C++14 onward, but easily implemented today with both g++ and Clang (see Live Example at the end of the answer)Here is the code
Live Example
Try
boost::mpl::range_c<int, 0, N>
docs.Use C++14 integral_sequence, or its invariant index_sequence
UPDATE: You may use std::array:
In C++14 it can be easily done with a
constexpr
constructor and a loop:using boost preprocessor, it's very simple.
OUTPUT: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24