Thijser Thijser - 2 months ago 6
C++ Question

c++ populate array with predefined values in a clever way

I'm looking for a way to populate an array with elements of values at compile time rather then run time. So what I'm looking for is something like this

#define numbar
Bar foo[] = {Bar(0),Bar(1)....Bar(numbar)}

Does c++ have any way to do this? Perhaps using macro's or something like that?


Assuming c++14:

constexpr auto num_bars = 100;

class Bar {
    constexpr Bar(int i);

template <std::size_t ...I>
constexpr auto generate_bars_impl(std::index_sequence<I...>) {
    return {Bar(I)...};

template <std::size_t N, typename Indices = std::make_index_sequence<N>>
constexpr auto generate_bars() {
   return generate_bars_impl(Indices());

constexpr auto generated = generate_bars<num_bars>();

This will give you an std::initializer_list in C++14. C++11: You should implement index_sequence and I think that initializer_list has no constexpr constructor.