List-initialization of containers of user-defined types does not behave as I would expect. See this snippet:
#include <array>
struct A {
char C;
int s;
};
int main(int argc, char * argv[]) {
A x = {'x'}, y = {'y'};
std::array<int, 2> i = {1, 2}; // Ok
std::array<A, 2> a = {x, y}; // Ok
//std::array<A, 2> b = { {'x',1000}, {'y',2000} }; // Error: too many initializers!!!
std::array<A, 2> c = { A{'x',1000}, A{'y',1000} };
std::array<A, 2> d = {{ {'x',1000}, {'y',1000} }}; // Ok!!
std::array<A, 2> e = {'x', 2000, 'y', 5000}; // Ok!!
}
I can initialize i as if it were a fundamental array. I can do the same with a, as long as they are variables. But I cannot initialize b without specifying the type A, such as in c.
To initialize an
std::arraywithout explicitly stating the typeA, I have to add another pair of braces. What is the logic behind the need for double braces? Why can it not be initialized with a single pair of braces surrounding the list, as inb?Also, surprisingly
cworks and it only yields two objects! Intuitively, I would expect thatewould yield error because there are 4 initial values for a maximum of 2 objects, but instead the compiler fills in the members ofAcorrectly! Why does this happen?