1

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.

Zorglub29
  • 6,979
  • 6
  • 20
  • 37
  • If you aren't doing it in a template, it's a non-starter. https://stackoverflow.com/a/46512580/817643 – StoryTeller - Unslander Monica Oct 20 '20 at 07:15
  • Your code is ill-formed, no diagnostic required, because of this: http://eel.is/c++draft/temp.res#general-8.1 The only sensible use-case for this if `val` depends on a template parameter, and if it is, the code will start working. – HolyBlackCat Oct 20 '20 at 07:16
  • 2
    it is difficult to project from your non-working example to your real case. What exactly do you expect from a "constexpr conditional static assertion" (when outside of a template) ? Is your aim to set a flag somewhere and then fail depending on that flag? Why not `static_assert( val == 1 && val > 0)` ? (ie no `if constexpr`) – 463035818_is_not_an_ai Oct 20 '20 at 07:29
  • Ok, so after a bit of reading in the directions pointed, it looks like the reason for this "problem" is that the branch is not really discarded, i.e. the compiler still sees it even if it is within a constexpr if with a condition that evaluates to false, right? And the only way to really not see this branch would be to use some template metaprogramming instead? – Zorglub29 Oct 22 '20 at 11:20
  • I was surprised by this as what I wanted was to "replace an #if macros with a constexpr if". But then it seems that this is not really possible actually with a constexpr if. – Zorglub29 Oct 22 '20 at 11:21

0 Answers0