I need to run a function with N boolean variables, I want to make them constexpr in order to exterminate comparisons and save the code from branch prediction failure.
What I mean is:
templateFunc<b1, b2, b3, b4 ...>(args...);
as the b1..bn variables are just boolean variables and may have only 2 states, I could write something like this:
if (b1 && b2)
templateFunc<true, true>(args...);
else if (b1 && !b2)
templateFunc<true, false>(args...);
else if (!b1 && b2)
templateFunc<false, true>(args...);
else
templateFunc<false, false>(args...);
The problem is obvious, I'd need 64 calls for 5 variables.. Any solution?
With std::variant
(C++17), you might do the dynamic dispatch via std::visit
:
// helper
std::variant<std::false_type, std::true_type> to_boolean_type(bool b)
{
if (b) return std::true_type{};
return std::false_type{};
}
and then
std::visit([&](auto... bs){templateFunc<bs...>(args...);},
to_boolean_type(b1), to_boolean_type(b2));