Search code examples
c++static-if

If statements on compile-time const value


I want to have code included in a function based on a compile time constant value, but static_if is not a construct in C++.

So I can write functions like this

class TA {
public:
    template<bool flag>
    void func() {
        if(flag)
            a++;
    }

    int a;
};


int main() {
    TA a;
    a.func<true>();
    a.func<false>();
}

And I want to have a guarantee that the compiler makes two functions. One where 'if(flag) a++' is compiled into the function and one where it is not.

Is it possible to get this guarantee based on the C++17 standard, or am I at the mercy of the compiler vendor?

Thanks.


Solution

  • In actual fact, C++17 does include exactly what you're asking about - it's callled if constexpr.

    You can use it anywhere your condition can be evaluated at compile time (such as template instantiation):

    class TA {
    public:
        template<bool flag>
        void func() {
            if constexpr (flag)
                a++;
        }
    
        int a;
    };
    

    However, as others have said, in this example you're unlikely to gain much as the compiler can often optimize stuff like this.