[英]How to initialize std::array member in constructor initialization list when the size of the array is a template parameter
在以下示例中,我需要在 A::A(H h) 构造函数初始化程序列表中初始化 std::array (因为 class H 没有默认构造函数),但我不能使用初始化程序来完成列表,因为数组大小是模板参数。
有没有解决的办法?
#include <array>
using namespace std;
struct Hash {
const vector<int> &data;
Hash(const vector<int> &data)
: data(data) {
}
uint64_t operator()(int id) const {
return data[id];
}
};
template <class H, size_t N>
class A {
public:
A(H h) {
}
std::array<H, N> hashes;
};
int main () {
vector<int> data{1, 2, 3, 4};
A<Hash, 4> a{Hash(data)};
}
提供std::index_sequence
是为了简化创建和扩展大小不固定的包的元编程任务。 使用std::make_index_sequence
并将构造委托给一些推断包的私有构造函数:
A(H h) : A(h, std::make_index_sequence<N>{}) {}
template <std::size_t... i>
A(H h, std::index_sequence<i...>) : hashes{((void)i, h)...} {}
这里, ((void)i, h)
是一个逗号表达式,计算结果为h
,但由于我们在其中提到了包i
,因此可以使用...
对其进行扩展。 结果是h
的N
个副本( i
的每个元素一个)。 这种扩展发生在一个花括号初始化列表中,因此结果是一个包含N
个h
副本的花括号初始化列表,然后它将初始化hashes
成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.