std::array 的内联初始化有什么问题?
What's wrong with this inline initialization of std::array?
考虑以下声明:
#include <array>
struct X
{
//std::array<bool,3> arr={false,false,false};
bool brr[3]={false,false,false};
};
按原样,它可以通过 g++ 5.2 正常编译。但是如果我取消注释 std::array
,我会得到一个错误:
test.cpp:5:46: error: array must be initialized with a brace-enclosed initializer
std::array<bool,3> arr={false,false,false};
^
test.cpp:5:46: error: too many initializers for ‘std::array<bool, 3u>’
OTOH,这个声明在 main()
中没有问题。此外,以下初始化确实在 struct X
:
内部起作用
std::array<bool,3> arr={{false,false,false}};
为什么我不能在结构定义中使用带单括号的简单初始化?
这看起来像是一个 gcc 错误,请参阅:Bug 65815 - brace elision doesn't work in NSDMI。报告说:
On Page 975 of "The C++ Programming Language", 4th edition, Bjarne
Stroustrup says:
"An array can be initialized by an initializer list: array a1 =
{ 1, 2, 3 };"
and Clang (V 3.5) accepts it. However, G++ 4.9.2 thinks this is an
error:
"error: array must be initialized with a brace-enclosed initializer
const std::array<double, 3> _ar0val = {1.0, -1.0, 1.0};"
问题已缩小为以下测试用例:
struct array {
int data [2];
};
struct X {
array a = { 1, 2 };
};
看起来修复在 head 版本中,OP 代码在该版本中有效,see it live。
如错误报告中所述,使用内部大括号是一种可能的解决方法:
std::array<bool,3> arr={ {false,false,false} };
^ ^
考虑以下声明:
#include <array>
struct X
{
//std::array<bool,3> arr={false,false,false};
bool brr[3]={false,false,false};
};
按原样,它可以通过 g++ 5.2 正常编译。但是如果我取消注释 std::array
,我会得到一个错误:
test.cpp:5:46: error: array must be initialized with a brace-enclosed initializer
std::array<bool,3> arr={false,false,false};
^
test.cpp:5:46: error: too many initializers for ‘std::array<bool, 3u>’
OTOH,这个声明在 main()
中没有问题。此外,以下初始化确实在 struct X
:
std::array<bool,3> arr={{false,false,false}};
为什么我不能在结构定义中使用带单括号的简单初始化?
这看起来像是一个 gcc 错误,请参阅:Bug 65815 - brace elision doesn't work in NSDMI。报告说:
On Page 975 of "The C++ Programming Language", 4th edition, Bjarne Stroustrup says:
"An array can be initialized by an initializer list: array a1 = { 1, 2, 3 };"
and Clang (V 3.5) accepts it. However, G++ 4.9.2 thinks this is an error:
"error: array must be initialized with a brace-enclosed initializer const std::array<double, 3> _ar0val = {1.0, -1.0, 1.0};"
问题已缩小为以下测试用例:
struct array {
int data [2];
};
struct X {
array a = { 1, 2 };
};
看起来修复在 head 版本中,OP 代码在该版本中有效,see it live。
如错误报告中所述,使用内部大括号是一种可能的解决方法:
std::array<bool,3> arr={ {false,false,false} };
^ ^