c++metaprogrammingarray-initialization

Compilation-time initialization of an array of struct with the information of another array


Let Foo be a structure holding an integer.

Now, I need to initialize at compilation time an array of Foo from the values coming from an array of integers.

Of course, one can hand-write it but having a generic way to do it (with some ArrayInitializer feature) would be of great help.

struct Foo { int n; };

constexpr int N = 3; // not necessary a literal but could come from a type trait value

int values [N] = {1,2,4};

// hand-written array initialization
Foo objects[N] = { Foo{values[0]}, Foo{values[1]}, Foo{values[2]} };

// is it possible to make it automatically ?
// Foo objects[N] = ArrayInitializer (N,objects,value);

int main () {}

Question: is it possible with meta-programming to design such an ArrayInitializer feature ? Or is it simply impossible and what is the reason why ?


Solution

  • With std::array<Foo, N>, you might do something like:

    template <std::size_t N>
    constexpr std::array<Foo, N> make_foo_array(const int(& arr)[N])
    {
        return [&]<std::size_t...Is>(std::index_sequence<Is...>){
            return array<Foo, N>{{ Foo(arr[Is])... }};
        }(std::make_index_sequence<N>());
    }
    

    Above requires C++20, but can be rewritten for other standards.