-1

我有以下代码。基本上我想使用聚合初始化语法初始化非 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
}

海合会错误:

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 ‘&lt;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 ‘&lt;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 ‘&lt;brace-enclosed initializer list>’ to ‘OtherClass<2u>&&’

我的问题:上面的代码正确吗?似乎 std::array 是一个聚合,构造它的数据成员应该没有问题。也许这是GCC中的一个错误?

编辑

OtherClass<2>{{ TheClass{1, 2}, TheClass{2, 3} }};当然可以,但我不想使用它,因为我必须在很多地方构建类。C++11 应该支持省略TheClass. 另请参阅此问题

4

1 回答 1

2

std::array是一个包含数组的聚合,因此您需要一对额外的大括号来从常规数组初始化它:

{1,2}               // TheClass
{{1,2},{2,3}}       // TheClass[2]
{{{1,2},{2,3}}}     // std::array<TheClass,2>
{{{{1,2},{2,3}}}}   // OtherClass<2>

然而,旧版本的 GCC 似乎仍然在为此苦苦挣扎:4.5.1 拒绝它,而 4.6.1 接受它。

于 2012-01-12T17:49:11.820 回答