Is "constexpr if" better than switch statement?

C ++ 17 introduces "constexpr if" which is generated depending on the compilation condition.

Does this mean that it is better to use "constexpr if" in template functions than a switch statement?

For example:

template<int val> void func()
{
    if constexpr(val == 0) {} else
    if constexpr(val == 1) {} else
    ...
    if constexpr(val == k) {} else {}
}
// vs
template<int val> void func()
{
    switch (val)
    {
        case 0:
            break;
        case 1:
            break;
        ...
        case k:
            break;
        default:
            break;
    }
}

      

+3


source to share


1 answer


if constexpr

was introduced to eliminate some branches that are poorly formed if the condition is false. In your case, you are only doing some operations with int

, so no branch should be poorly formed if the other is well formed. It doesn't make sense to use it.

As stated above, if constexpr

there is no real benefit to using it beyond the assurance that the compiler will remove every other branch. But I would expect a good optimized compiler to do this with switch

, since it val

is a constant when created func

.



I would use an operator switch

, but that's just me. So, choose the one that you like.

+6


source







All Articles