Using std::array with initialization lists

匿名 (未验证) 提交于 2019-12-03 08:59:04

问题:

Unless I am mistaken, it should be possible to create a std:array in these ways:

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

And yet, using GCC 4.6.1 I am unable to get any of these to work. The compiler simply says:

expected primary-expression before ',' token 

and yet initialization lists work just fine with std::vector. So which is it? Am I mistaken to think std::array should accept initialization lists, or has the GNU Standard C++ Library team goofed?

回答1:

std::array is funny. It is defined basically like this:

template struct std::array {   T a[size]; }; 

It is a struct which contains an array. It does not have a constructor that takes an initializer list. But std::array is an aggregate by the rules of C++11, and therefore it can be created by aggregate initialization. To aggregate initialize the array inside the struct, you need a second set of curly braces:

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

Note that the standard does suggest that the extra braces can be elided in this case. So it likely is a GCC bug.



回答2:

To add to the accepted answer:

std::array a1{'a', 'b'}; std::array a2 = {'a', 'b'}; std::array a3{{'a', 'b'}}; std::array a4 = {{'a', 'b'}}; 

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

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

the above requires double braces to compile. The version with single braces 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 ‘’ to ‘std::array

I'm not sure what aspect of type inference/conversion makes things work this way, or if this is a quirk of GCC's implementation.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!