plasmacel plasmacel - 1 month ago 16
C++ Question

Aggregate initialization of std::array of subobjects with nested initializer lists

What is the correct way to initialize an aggregate type (such as

std::array
) and its subobjects with nested braced initializer lists? I don't want to call the constructors of the sub-type(s) directly.

This is a recurring issue and I'm always surprised that the code below doesn't work, since the type of the elements is specified, so the proper constructor can be deduced by the compiler.

Note that the example type
A
is not necessary to be an aggregate (but of course it must support braced initializer-lists).

#include <array>

struct A
{
int values[4];
};

int main()
{
std::array<A, 2> arr{{ 0, 1, 2, 3 }, { 4, 5, 6, 7 }};

// Works only if A is an aggregate, also looks confusing, I don't want to do this
//std::array<A, 2> arr{ 0, 1, 2, 3, 4, 5, 6, 7 };

// I don't want to do this neither
//std::array<A, 2> arr{A{ 0, 1, 2, 3 }, A{ 4, 5, 6, 7 }};

return 0;
}


But all I get is the error

error: too many initializers for 'std::array<A, 2ul>'

Answer

You could add braces around initialization of subobject, like

std::array<A, 2> arr{{{ 0, 1, 2, 3 }, { 4, 5, 6, 7 }}};
Comments