码:
std::vector<int> x{1,2,3,4};
std::array<int, 4> y{{1,2,3,4}};
Run Code Online (Sandbox Code Playgroud)
为什么我需要std :: array的双花括号?
编译下面的代码时,我在VC2010中遇到错误C2078.
struct A
{
int foo;
double bar;
};
std::array<A, 2> a1 =
// error C2078: too many initializers
{
{0, 0.1},
{2, 3.4}
};
// OK
std::array<double, 2> a2 = {0.1, 2.3};
Run Code Online (Sandbox Code Playgroud)
我发现正确的语法a1是
std::array<A, 2> a1 =
{{
{0, 0.1},
{2, 3.4}
}};
Run Code Online (Sandbox Code Playgroud)
问题是:为什么需要额外的括号a1但不是必需的a2?
更新
这个问题似乎并不特定于std :: array.一些例子:
struct B
{
int foo[2];
};
// OK
B meow1 = {1,2};
B bark1 = {{1,2}};
struct C
{
struct
{
int a, b;
} …Run Code Online (Sandbox Code Playgroud) 我现在正在阅读C++ 14的标准草案,也许我的法律术语有点生疏,但我找不到允许初始化如下所示
std::array<int, 3> arr{1,2,3};
Run Code Online (Sandbox Code Playgroud)
合法.(编辑:显然上面是C++ 11中的合法语法.)目前在C++ 11中我们必须将std :: array初始化为
std::array<int, 3> arr{{1,2,3}}; // uniform initialization + aggregate initialization
Run Code Online (Sandbox Code Playgroud)
要么
std::array<int, 3> arr = {1,2,3};
Run Code Online (Sandbox Code Playgroud)
我以为我听说他们在C++ 14中放松了规则,所以我们在使用统一初始化时不必使用双括号方法,但我找不到实际的证据.
注意:我关心这个的原因是因为我目前正在开发一个multi_array类型,并且不想像它一样初始化它
multi_array<int, 2, 2> matrix = {
{{ 1, 2 }}, {{ 3, 4 }}
};
Run Code Online (Sandbox Code Playgroud)