I have this call to the sort
C++ algorithm:
std::sort(std::execution::par_unseq, vec.begin(), vec.end());
Now I would like to parametrize the execution policy:
std::sort(executionPolicy, vec.begin(), vec.end());
However, std::execution::seq, std::execution::par, std::execution::par_unseq, std::execution::unseq
are objects of different type, respectively: std::execution::sequenced_policy, std::execution::parallel_policy, std::execution::parallel_unsequenced_policy, std::execution::unsequenced_policy
.
How can I use a variable to store objects belonging to different classes which do not share a base class?
The approach I've used for this has been to use std::variant
and std::visit
for this purpose.
using parallel_policy_holder = std::variant
<
std::execution::sequenced_policy,
std::execution::parallel_policy,
std::execution::parallel_unsequenced_policy,
std::execution::unsequenced_policy
>;
void foo(parallel_policy_holder policy, std::vector<int> const& input)
{
std::visit
(
[&](auto policy_real) { std::sort(policy_real, input.begin(), input.end()); },
policy
);
}