[英]Excess elements in struct initializer when nested std::array
I'm getting Excess elements in struct initializer
on the return
line of the following: 我在以下
return
行的Excess elements in struct initializer
获取了Excess elements in struct initializer
:
using triangleColor = std::array<std::array<float, 4>, 3>;
triangleColor colorBlend(TriangleColorBlend c){
switch (c) {
case TriangleColorBlend::white:
return {{1.0,1.0,1.0,1.0},{0.7,0.7,0.7,1.0},{0.5,0.5,0.5,1.0}};
break;
... // other cases
}
}
I was hoping the curly-brace literal would work in the nested fashion, as it works fine if I do this with just a single std::array, not nested. 我希望花括号文字能够以嵌套的方式工作,因为如果我只使用一个std :: array而不是嵌套,它可以正常工作。
Is the above simply not possible, and why not? 以上根本不可能,为什么不呢?
Note, the suggested duplicate doesn't really address the odd behavior of std::array in a nested situation. 注意,建议的副本并没有真正解决嵌套情况下std :: array的奇怪行为。
triangleColor colorBlend(TriangleColorBlend c) {
switch (c) {
case TriangleColorBlend::white:
return {{
{{ 1.0f, 1.0f, 1.0f, 1.0f }},
{{ 0.7f, 0.7f, 0.7f, 1.0f }},
{{ 0.5f, 0.5f, 0.5f, 1.0f }}
}};
default:
throw std::invalid_argument("c");
}
}
There were two issues with your code: 您的代码存在两个问题:
colorBlend
had no return value for the default case. colorBlend
没有默认情况的返回值。 You are missing a set of brackets. 你缺少一组括号。
return {{1.0,1.0,1.0,1.0},{0.7,0.7,0.7,1.0},{0.5,0.5,0.5,1.0}};
Should be 应该
return {{{1.0,1.0,1.0,1.0},{0.7,0.7,0.7,1.0},{0.5,0.5,0.5,1.0}}};
You can see it working in this minimal example 你可以看到它在这个最小的例子中工作
Another work around: 另一项工作:
triangleColor colorBlend(TriangleColorBlend c){
using t1 = std::array<float, 4>;
switch (c) {
case TriangleColorBlend::white:
return {t1{1.0,1.0,1.0,1.0},t1{0.7,0.7,0.7,1.0},t1{0.5,0.5,0.5,1.0}};
break;
default:
break;
}
return triangleColor{};
}
The answer to the question of why 对于为什么这个问题的答案
return {{1.0,1.0,1.0,1.0},{0.7,0.7,0.7,1.0},{0.5,0.5,0.5,1.0}};
does not work can be found at https://stackoverflow.com/a/8192275/434551 : 不起作用可以在https://stackoverflow.com/a/8192275/434551找到:
std::array
is an aggregate by the rules of C++11, and therefore it can be created by aggregate initialization.std::array
是C ++ 11规则的聚合,因此可以通过聚合初始化来创建。 To aggregate initialize the array inside the struct, you need a second set of curly braces.要聚合初始化结构内的数组,需要第二组花括号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.