简体   繁体   中英

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>'

You could add braces around initialization of subobject, like

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

std::array<A, 2> arr{{ 0, 1, 2, 3 }, { 4, 5, 6, 7 }}; doesn't work, because for brace elision ,

the braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent initializer clauses are used to initialize the following members of the object.

Note that the 1st initializer clause { 0, 1, 2, 3 } could be used for the initialization of the whole inner array of std::array (the remaining elements will be initialized to zero). Then { 4, 5, 6, 7} becomes the excess clause.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM