C++初始化列表和可变参数模板

6

我想创建一个数组:

template < typename T, typename ... A > struct a {
  T x [1 + sizeof... (A)];
  a () = default;
  a (T && t, A && ... y) : x { t, y... } {}
};

int main () {
  a < int, int > p { 1, 1 }; // ok
  a < a < int, int >, a < int, int > > q { { 1, 1 }, { 3, 3 } }; // error: bad array initializer
}

为什么它不能编译?(使用g++ 4.6测试)
1个回答

2
我相信这是一个bug。在提供构造函数参数时,可以使用{}代替()。因此,您的代码应该没有问题:
int main ()
{
    // this is fine, calls constructor with {1, 1}, {3, 3}
    a<a<int, int>, a<int, int>> q({ 1, 1 }, { 3, 3 });

    // which in turn needs to construct a T from {1, 1},
    // which is fine because that's the same as:
    a<int, int>{1, 1}; // same as: a<int, int>(1, 1);

    // and that's trivially okay (and tested in your code)

    // we do likewise with A..., which is the same as above
    // except with {3, 3}; and the values don't affect it
}

所以整个事情应该没问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接