Reputation: 5848
I have a constexpr
array like this:
constexpr std::array<int, 4> BASES_TO_CHECK = { 8, 16, 32, 64 };
I would like to do something akin to:
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));
}
However, as the variable is used as a template parameter, so that won't work. I have ended up doing this:
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))
};
And this works, but is relying on me not changing the number of elements in the BASES_TO_CHECK
without also manually updating the part of the code where calc
array is initialised.
Upvotes: 2
Views: 89
Reputation: 15878
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()>{});
Upvotes: 3