Search code examples
c++string-literalsstatic-assert

How to pass a not explicitly string literal error message to a static_assert?


I have a few static asserts in different places in code.

static_assert(bool_constexpr_1, error_message);
...
static_assert(bool_constexpr_2, error_message);

And want all of them to share the same error_message.

The first solution is to copy-paste the message.

The second one is to #define the error_message.

Is there something better?

P.S. I expected static constexpr auto to work, yet it failed.


Solution

  • You either have to copy-paste the literal, or use the preprocessor. Per [dcl.dcl]/1 The grammar of static_assert is defined as

    static_assert-declaration:
          static_­assert ( constant-expression ) ;
          static_­assert ( constant-expression , string-literal ) ;
    

    So you either provide a string literal, or you don't. There is no other way to use it.