gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:44:32 24 4
gpt4 key购买 nike

我想创建一个数组:

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 测试)

最佳答案

我很确定这是一个错误。 {} 可以代替 () 来为构造函数提供参数。因此你的代码应该没问题:

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
}

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

关于C++ 初始化列表和可变参数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5475040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com