1

I have code as below

struct A {int i; int j;}

int main()
{
    array<A, 2> a;
    a = {{1,2},{3,4}}; //compilation error: not take a right-hand operand of 
                       //type 'initializer list' (or no acceptable conversion)
}

I think it is a nested aggregate initialization, but why not work? And How to make a = {{1,2},{3,4}} work by changing the code?

Find way work

a = { {{1,2},{3,4}} }; 

Don't know why?

user1899020
  • 13,167
  • 21
  • 79
  • 154

2 Answers2

2

Aggregate initialization is initialization. a has already been initialized via default initialization. You can't initialize it again (well, you could, but let's not get into the deep magic).

If you want this to work, you must apply the braced-init-list to the declaration of a, not afterwards.

However, if you want to assign to a, you can always do this:

a = decltype(a){{{1,2},{3,4}}}
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
0

As already stated you're not initializing but rather assigning, consequently aggregate initialization is out of play here. This could work however, if you could give a little help to the compiler:

std::array<A, 2> a;
a = {A{1,2}, A{3,4}};

Live Demo

101010
  • 41,839
  • 11
  • 94
  • 168