Search code examples
c++static-assert

Can I disable static asserts?


I have some rather costly static_assert calls scattered throughout my code. While these are valuable, they are often superfulous and significantly contribute to compile time and memory usage.

Can I disable them?


Solution

  • Wrap them in the standard NDEBUG macro.

    #ifndef NDEBUG
    static_assert(...);
    #endif
    

    That way for release builds you can disable them just like regular assert. Although I don't really see a purpose to this.

    If you don't like wrapping up the calls in a macro, you can define a macro that does it for you:

    #ifndef STATIC_ASSERT
    #ifndef NDEBUG
    #define STATIC_ASSERT(...) static_assert(__VA_ARGS__)
    #else
    #define STATIC_ASSERT(...) static_assert(true, "")
    #endif // NDEBUG
    #endif // STATIC_ASSERT
    

    Usage is similar to a regular static_assert. Note that if your program defines a keyword and includes a standard library header then it is undefined behaviour to define a static_assert macro.