我有一个constexpr
数组,如下所示:
constexpr std::array<int, 4> BASES_TO_CHECK = { 8, 16, 32, 64 };
我想做些类似的事情:
std::array<std::thread, BASES_TO_CHECK.size()> calc;
for(size_t i = 0; i<BASES_TO_CHECK.size(); ++i)
{
calc[i]=std::thread(calculate<BASES_TO_CHECK[i]>, std::ref(recordMap[BASES_TO_CHECK[i]]), std::ref(counterMap.at(BASES_TO_CHECK[i])), std::ref(done));
}
但是,由于该变量用作模板参数,因此无法使用。我最终这样做了:
std::array<std::thread, BASES_TO_CHECK.size()> calc = {
std::thread(calculate<BASES_TO_CHECK[0]>, std::ref(recordMap[BASES_TO_CHECK[0]]), std::ref(counterMap.at(BASES_TO_CHECK[0])), std::ref(done)),
std::thread(calculate<BASES_TO_CHECK[1]>, std::ref(recordMap[BASES_TO_CHECK[1]]), std::ref(counterMap.at(BASES_TO_CHECK[1])), std::ref(done)),
std::thread(calculate<BASES_TO_CHECK[2]>, std::ref(recordMap[BASES_TO_CHECK[2]]), std::ref(counterMap.at(BASES_TO_CHECK[2])), std::ref(done)),
std::thread(calculate<BASES_TO_CHECK[3]>, std::ref(recordMap[BASES_TO_CHECK[3]]), std::ref(counterMap.at(BASES_TO_CHECK[3])), std::ref(done))
};
这可行,但要依靠我不更改BASES_TO_CHECK
中元素的数量,而无需手动更新初始化calc
数组的代码部分。
答案 0 :(得分:3)
template<std::size_t... i>
std::array<std::thread, BASES_TO_CHECK.size()> gen_impl(std::index_sequence<i...>) {
return {
std::thread(calculate<BASES_TO_CHECK[i]>,
std::ref(recordMap[BASES_TO_CHECK[i]]),
std::ref(counterMap.at(BASES_TO_CHECK[i])),
std::ref(done)
)...
};
}
auto calc = gen_impl(std::make_index_sequence<BASES_TO_CHECK.size()>{});