如何初始化模板大小的数组
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...}}
{ }
相关文章:
- C++使用整数的压缩数组初始化对象
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 字节数组初始化会导致 DirectX 崩溃
- 使用 new 和 值进行数组初始化,但没有显式数量的元素
- 运行时C++数组初始化问题
- 使用带有参数包的数组的成员数组初始化类
- 仅通过C++中数组初始化的不同方法,即可在同一输入上获得两个不同的答案
- C++ 2 个指针数组初始化 C2440
- C++结构字符数组初始化
- C++中的多维数组初始化
- constexpr数组初始化
- C++引物动态数组初始化程序的数目超过大小
- 使用std::index_sequence对std::数组初始化进行包扩展
- 当 std 数组初始化太小时,C++会引发错误吗?
- 如何确定结构数组初始化的大小?
- Qt并发错误:数组初始化需要大括号括起来的初始值设定项列表
- 此代码中的数组初始化样式是什么?这是标准的吗?
- C++ 使用数组初始化时的 STL 向量内存管理