In C++17, a number of functions in the algorithm
header now can take an execution policy. I can for example define and call a function like this:
template <class ExecutionPolicy>
void f1(const std::vector<std::string>& vec, const std::string& elem, ExecutionPolicy&& policy) {
const auto it = std::find(
std::forward<ExecutionPolicy>(policy),
vec.cbegin(), vec.cend(), elem
);
}
std::vector<std::string> vec;
f1(vec, "test", std::execution::seq);
However I haven't found a good way to use different policies at runtime. For example when I want to use a different policy depending on some input file.
I toyed around with variants, but in the end the problem was always the different types of std::execution::seq
, std::execution::par
and std::execution::par_unseq
.
A working but cumbersome solution would look like this:
void f2(const std::vector<std::string>& vec, const std::string& elem, const int policy) {
const auto it = [&]() {
if (policy == 0) {
return std::find(
std::execution::seq,
vec.cbegin(), vec.cend(), elem
);
}
else if (policy == 1) {
return std::find(
std::execution::par,
vec.cbegin(), vec.cend(), elem
);
}
else{
return std::find(
std::execution::par_unseq,
vec.cbegin(), vec.cend(), elem
);
}
};
}
f2(vec, "test", 0);
Is there any more elegant solution I'm overlooking?
edit: maybe I should be more precise. Let's say the goal is to save the policy in a variable that can have either of the three policies. That variable should be a parameter to the function.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…