[英]How to initialize a template sized array?
我想初始化一个模板大小的对象数组,没有默认的构造函数,如下面的代码所示:
#include <array>
template<std::size_t N>
class Foo
{
public:
class Bar
{
Foo<N> & _super;
public:
Bar(Foo<N> *super) :
_super(*super)
{
}
};
std::array<Bar, N> _array;
Foo(void) :
_array{{}} // We need {this, ...} N times
{
}
};
int main(void)
{
Foo<3> foo;
(void)foo;
return 0;
}
这是一种说法:“我想要一个N个对象的数组,所有对象都使用相同的参数进行初始化”? 我认为模板元编程有一种方法,但我无法想象如何做到这一点。
在make_index_sequence
帮助下,一切皆有可能:
Foo() : Foo(std::make_index_sequence<N>()) {}
template <size_t... I> Foo(std::index_sequence<I...> ) : _array{((void)I, this)...} {}
注意_array
构造函数中的逗号运算符(,) - 由@Quentin提供(而不是函数调用)。
你可以只继续添加一个this
在同一时间,直到你有N
他们的,在这一点上,你只是初始化_array
:
Foo()
: Foo(this)
{ }
private:
template <class... T, std::enable_if_t<(sizeof...(T) < N), void*> = nullptr>
Foo(T... args)
: Foo(args..., this)
{ }
template <class... T, std::enable_if_t<(sizeof...(T) == N), void*> = nullptr>
Foo(T... args)
: _array{{args...}}
{ }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.