How to use static asserts with if constexpr logics?

99 views Asked by At

I would like to use some static_assert checking, with conditions that depend on some constexpr logics. I thought that something like this may work:

int main(){
    constexpr int val = 1;

    if constexpr (val == 1){
        static_assert(val > 0);
    }

    if constexpr (val == 2){
        static_assert(val > 1);
    }
}

As it should be possible at compile time to determine that only the first assertion should be checked. However, I get:

$ g++ -Wall -std=c++1z main.cpp 
main.cpp: In function ‘int main()’:
main.cpp:13:9: error: static assertion failed
         static_assert(val > 1);
         ^~~~~~~~~~~~~

which I am a bit surprised about, I would have thought the compiler smart enough to understand at compile time that the second if should not be taken.

So my question is, any idea how to obtain a pattern that performs this kind of "constexpr conditional static assertion"?

A few infos on my compiler version, if this may be useful:

$ g++ --version
g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0

PS: of course, this is a trivial / ridiculous test, but I am interested in how to obtain a pattern like this, for more complex cases.

0

There are 0 answers