Search code examples
c++c++11static-assert

Is there any way to slip a static_assert into an expression in ISO C++11?


In C++11 it is legal to write, for instance:

int b = (some_function_returning_void(), 1020);

And you'll get back 1020. But it won't let you write:

int b = (static_assert(2 > 1, "all is lost"), 304);

The documentation explains the legal spots where static_assert (a keyword, apparently) can occur:

A static assert declaration may appear at block scope (as a block declaration) and inside a class body (as a member declaration)

Just for the heck of it I tried a couple things until this worked:

int b = ({static_assert(2 > 1, "all is lost"); 304;});

But with -Wpedantic I get "warning: ISO C++ forbids braced-groups within expressions". Interestingly, these are called "statement expressions" and used in the Linux kernel.

But let's imagine I want to stay -Wpedantic. Are there any clean workarounds?


Solution

  • As @dyp mentioned in the comments, you can abuse the comma operator and a lambda-expression :

    ([]{static_assert(true,"");}, 42)
    

    Live on Coliru