简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM