1

I have the following function

template <bool c>
void func()
{
    ...
    if (c) {
        // do something
    } else {
        // do something else
    }
}

This function is to be used several time inside a loop:

for (...) {
    func<true>();
}

I would like to know it the if inside func is done compile-time, run-time, or if it is left to the compiler.

0

1 Answer 1

5

The compiler may or may not optimize your code since it knows what c is at compile time. The only way to actually know would be to look at the generated assembly code to see if the branch was removed or not. That said, C++17 introduced constexpr if which is guaranteed to evaluate the condition at compile time and discard the branch that is not taken. That would make your function look like

template <bool c>
void func()
{
    // ...
    if constexpr(c) {
        // do something if c is true, discarded otherwise
    } else {
        // do something if c is false, discarded otherwise
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.