使用std :: array和初始化列表 [英] Using std::array with initialization lists
问题描述
除非我错了,应该可以用这些方法创建一个std:数组:
Unless I am mistaken, it should be possible to create a std:array in these ways:
std::array<std::string, 2> strings = { "a", "b" };
std::array<std::string, 2> strings({ "a", "b" });
然而,使用GCC 4.6.1我无法获得任何这些工作。编译器简单地说:
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
,但初始化列表与std :: vector一样正常工作。那是什么呢?我错误地认为std :: array应该接受初始化列表,或者有GNU标准C ++库团队goofed?
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?
推荐答案
code> std :: array 很有趣。它定义基本上是这样的:
std::array
is funny. It is defined basically like this:
template<typename T, int size>
struct std::array
{
T a[size];
};
这是一个包含数组的结构体。它没有一个构造函数,它接受一个初始化列表。但是 std :: array
是通过C ++ 11的规则的聚合,因此它可以通过聚合初始化创建。要集合初始化结构中的数组,您需要第二组花括号:
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<std::string, 2> strings = {{ "a", "b" }};
请注意,标准确实建议在这种情况下可以省略额外的大括号。所以很可能是一个GCC错误。
Note that the standard does suggest that the extra braces can be elided in this case. So it likely is a GCC bug.
这篇关于使用std :: array和初始化列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!