if constexpr: Metaprogramming Made Easy#
Problem#
is_even()evaluation inconstexprcontext is only guaranteed when assigning to aconstexprvariableHow to use in
if?
#include <iostream>
constexpr bool is_even(unsigned num)
{
return num % 2 == 0;
}
int main()
{
constexpr bool even = is_even(6); // <-- workaround
if (even) // <-- intelligent compiler not guaranteed
std::cout << "even\n";
else
std::cout << "odd\n";
return 0;
}
This is clumsy
Still no guarantee because compilers are not required to treat constant conditions specially
Solution#
#include <iostream>
constexpr bool is_even(unsigned num)
{
return num % 2 == 0;
}
int main()
{
if constexpr (is_even(6)) // <-- better
std::cout << "even\n";
else
std::cout << "odd\n";
return 0;
}