C++ use templates to avoid compiler from checking a boolean

Viewed 5730

Let's say I have a function:

template <bool stuff>
inline void doSomething() {
    if(stuff) {
        cout << "Hello" << endl;
    }
    else {
        cout << "Goodbye" << endl;
    }
}

And I call it like this:

doSomething<true>();
doSomething<false>();

It would pring out:

Hello
Goodbye

What I'm really wondering is does the compiler fully optimize this? When I call the templated function with true, will it create a function that just outputs "Hello" and avoids the if statement and the code for "Goodbye"?

This would be really useful for this one giant function I just wrote that's supposed to be very optimized and avoid as many unnecessary if statement checks as possible. I have a very good feeling it would, at least in a release build with optimizations if not in a debug build with no optimizations.

5 Answers
Related