Using std :: array with initialization lists

If I am mistaken, it should be possible to create an std array: {/ p>

std::array<std::string, 2> strings = { "a", "b" }; std::array<std::string, 2> strings({ "a", "b" }); 

And yet, using GCC 4.6.1, I cannot get them to work. The compiler simply says:

 expected primary-expression before ',' token 

and yet initialization lists work fine with std :: vector. So what is it? Am I mistaken in thinking that std :: array should accept initialization lists, or is the GNU Standard C ++ Library goofed command?

+45
c ++ c ++ 11 libstdc ++
Nov 19 2018-11-11T00:
source share
2 answers

std::array funny. It is defined mainly as follows:

 template<typename T, int size> struct std::array { T a[size]; }; 

This is the structure containing the array. It does not have a constructor that accepts a list of initializers. But std::array is an aggregate according to C ++ 11 rules, and therefore it can be created by aggregate initialization. To aggregate the initialization of an array inside a structure, you will need a second set of curly braces:

 std::array<std::string, 2> strings = {{ "a", "b" }}; 

Note that the standard indicates that in this case, you can remove additional curly braces. This is probably a GCC bug.

+71
Nov 19 2018-11-11T00:
source share

To add to the accepted answer:

 std::array<char, 2> a1{'a', 'b'}; std::array<char, 2> a2 = {'a', 'b'}; std::array<char, 2> a3{{'a', 'b'}}; std::array<char, 2> a4 = {{'a', 'b'}}; 

all work on GCC 4.6.3 (Xubuntu 12.01). However,

 void f(std::array<char, 2> a) { } //f({'a', 'b'}); //doesn't compile f({{'a', 'b'}}); 

this requires a double curly brace. The single brackets version results in the following error:

 ../src/main.cc: In function 'int main(int, char**)': ../src/main.cc:23:17: error: could not convert '{'a', 'b'}' from '<brace-enclosed initializer list>' to 'std::array<char, 2ul>' 

I'm not sure which aspect of the output / conversion type does the work this way, or if this is a fad of the GCC implementation.

+8
Sep 27 '12 at 8:11
source share