性病的嵌套集合初始化数组:: [英] Nested aggregate initialization of std::array
问题描述
我不知道,为什么 std_arr
的声明在以下code产生一个错误,而 c_arr
编译好:
I wonder, why declaration of std_arr
in the following code generates an error, while c_arr
compiles well:
struct S { int a, b; };
S c_arr[] = {{1, 2}, {3, 4}}; // OK
std::array<S, 2> std_arr = {{1, 2}, {3, 4}}; // Error: too many initializers
两者的std ::阵列
和取值
的集合体。从对CP preference.com 集合初始化:
Both std::array
and S
are aggregates. From aggregate initialization on cppreference.com:
如果初始化子句是嵌套的支撑,初始化列表(这是不是一个前pression并没有类型),对应的类成员
本身就是一个聚集:集合初始化是递归的
If the initializer clause is a nested braced-init-list (which is not an expression and has no type), the corresponding class member is itself an aggregate: aggregate initialization is recursive.
为什么这个初始化的std ::阵列
的不编译?
Why this initialization of std::array
does not compile?
推荐答案
在总初始化的括号是可选的大部分,所以你可以写:
The braces in aggregate initialisation are largely optional, so you can write:
S c_arr[] = {1, 2, 3, 4}; // OK
std::array<S, 2> std_arr = {1, 2, 3, 4}; // OK
如果您添加括号,不过,那么大括号视为适用于下一子对象。不幸的是,当你开始筑巢,这导致愚蠢code是有效的,而明智的code像你这样是无效的。
If you do add braces, though, then the braces are taken to apply to the next sub-object. Unfortunately, when you start nesting, this leads to silly code being valid, and sensible code like yours being invalid.
std::array<S, 2> std_arr = {{1, 2, 3, 4}}; // OK
std::array<S, 2> std_arr = {1, 2, {3, 4}}; // OK
std::array<S, 2> std_arr = {1, {2}, {3, 4}}; // OK
这些都是好的。 {1,2,3,4}
是一个有效的初始化器的 S [2]
成员 std_arr
。 {2}
是好的,因为它是初始化一个 INT
和 {2企图}
是一个有效的初始化器。 {3,4}
被当作一个初始化器为取值
,而且它也是有效的。
These are all okay. {1, 2, 3, 4}
is a valid initialiser for the S[2]
member of std_arr
. {2}
is okay because it is an attempt to initialise an int
, and {2}
is a valid initialiser for that. {3, 4}
is taken as an initialiser for S
, and it's also valid for that.
std::array<S, 2> std_arr = {{1, 2}, {3, 4}}; // error
这是不行的,因为 {1,2}
被视为一个有效的初始化器的 S [2]
成员。其余的 INT
子对象初始化为零。
This is not okay because {1, 2}
is taken as a valid initialiser for the S[2]
member. The remaining int
sub-objects are initialised to zero.
您然后让 {3,4}
,但目前还没有更多的成员初始化。
You then have {3, 4}
, but there are no more members to initialise.
由于在评论中指出,
std::array<S, 2> std_arr = {{{1, 2}, {3, 4}}};
也有效。嵌套的 {{1,2},{3,4}}
是一个初始化器在 S [2]
会员。在 {1,2}
是第一个取值
元素的初始化器。在 {3,4}
是第二个取值
元素的初始化器。
also works. The nested {{1, 2}, {3, 4}}
is an initialiser for the S[2]
member. The {1, 2}
is an initialiser for the first S
element. The {3, 4}
is an initialiser for the second S
element.
<子>我假设在这里,的std ::阵列&LT; S,2 - ;
包含类型的数组成员 S [2]
,它确实目前的实现,并且我相信这是有可能成为保障的,但已被覆盖在此之前,不保证当前
I'm assuming here that std::array<S, 2>
contains an array member of type S[2]
, which it does on current implementations, and which I believe is likely to become guaranteed, but which has been covered on SO before and is not currently guaranteed.
这篇关于性病的嵌套集合初始化数组::的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!