【发布时间】:2012-02-09 00:16:07
【问题描述】:
我有以下代码。基本上,我想使用聚合初始化语法初始化非 POD 结构的 std::array。 g++ 4.6 和 4.7(最新的每周快照)都无法编译代码。
#include <array>
struct TheClass {
int a1, a2;
TheClass(int b1, int b2) : a1{b1}, a2{b2} {};
};
template<unsigned D>
struct OtherClass {
std::array<TheClass, D> a;
OtherClass(std::array<TheClass, 2> b) : a{b} {};
};
int main()
{
OtherClass<2>{{ {1, 2}, {2, 3} }}; //tried a lot of options here
}
GCC 错误:
v.cpp: In function ‘int main()’:
v.cpp:20:37: error: no matching function for call to ‘OtherClass<2u>::OtherClass(<brace-enclosed initializer list>)’
v.cpp:20:37: note: candidates are:
v.cpp:15:5: note: OtherClass<D>::OtherClass(std::array<TheClass, 2ul>) [with unsigned int D = 2u]
v.cpp:15:5: note: no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘std::array<TheClass, 2ul>’
v.cpp:11:8: note: constexpr OtherClass<2u>::OtherClass(const OtherClass<2u>&)
v.cpp:11:8: note: no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘const OtherClass<2u>&’
v.cpp:11:8: note: constexpr OtherClass<2u>::OtherClass(OtherClass<2u>&&)
v.cpp:11:8: note: no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘OtherClass<2u>&&’
我的问题:上面的代码正确吗?似乎 std::array 是一个聚合,构造它的数据成员应该没有问题。也许这是 GCC 中的错误?
编辑:
OtherClass<2>{{ TheClass{1, 2}, TheClass{2, 3} }}; 当然可以,但我不想使用它,因为我必须在很多地方构建类。 C++11 应该支持省略TheClass。另见this question。
【问题讨论】:
-
你试过
OtherClass<2>{{{ TheClass {1, 2}, TheClass {2, 3} }}};吗? -
请查看更新后的问题。当然可以,但是 C++11 应该支持省略
TheClass。 -
您的更新不包括我评论中的额外大括号。
标签: c++ constructor c++11 initializer-list