Search code examples
c++arrayscompiler-errorsstdarraylist-initialization

Why do I have to specify the type for each item at the initialization of std::array<SomeStruct, size> in C++


Given the SomeStruct as below:

struct SomeStruct {
    int i;
    char c;
};

Below does not compile.

int main() {
    std::array<SomeStruct,2> arr = {{3, 't'}, {3, 't'}}; 
}

But the code below works.

int main() {
    std::array<SomeStruct,2> arr = {SomeStruct{3, 't'}, SomeStruct{3, 't'}}; 
}

And this one works as well:

int main() {
    std::array<SomeStruct,1> arr = {{3, 't'}}; 
}

Why does this std::array<SomeStruct,2> arr = {{3, 't'}, {3, 't'}}; cause a compilation error?

Plus, is there a more concise way to put std::array<SomeStruct,2> arr = {SomeStruct{3, 't'}, SomeStruct{3, 't'}}? I don't want to use arr.fill(SomeStruct{3,'t'}) or a loop. I want to set all the items to the same SomeStruct{3, 't'} at initialization.


Solution

  • As a rule of thumb, if a std::array initialization doesn't seem to work, keep adding extra pairs of braces until it does...

    std::array<SomeStruct,2> arr = {{{3, 't'}, {3, 't'}}}; 
    

    The reasons behind this and the history are long and complicated, it boils down to contention between aggregate initialization (a wart from C compatibility) and non-aggregate list initialization (added in C++11).