Comma statement with static_assert ()

When trying to evaluate a comma operator with static_assertwhen argument compilation fails

void fvoid() {}

int main() {
    int a = (1, 2); // a=2
    int b = (fvoid(), 3); // b=3

    int d = ( , 5);
    //        ^
    // error: expected primary-expression before ',' token. OK

    int c = (static_assert(true), 4);
    //       ^~~~~~~~~~~~~
    // error: expected primary-expression before 'static_assert'. Why?
}

It static_assert()doesn't seem to even allow voidafter compilation. I could not find anything about this in the standard. Is there a way to use it with a comma operator, or use it according to another expression (without a semicolon)?

+4
source share
3 answers

No no. Language grammar requires a semicolon at the end of a static statement declaration.

N4140 §7 [dcl.dcl] / 1

static_assert declaration:

static_assert (expression constant, literal string );

+5
source

( )?

, static_assert.
, , , - - :

int main() {
    int c = ([]{ static_assert(true, "!"); }(), 4);
}

, - , true.
() ( ).
- . :

template<bool b>
void f() {
    int c = ([](){ static_assert(b, "!"); }(), 4);
    // ...
}

, , ( godbolt, ).

+3

You can simply wrap it in a block:

int c = ({ static_assert(true); }, 4);
+1
source

Source: https://habr.com/ru/post/1661092/


All Articles