quant
quant

Reputation: 23022

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?

Upvotes: 4

Views: 3234

Answers (2)

Rapptz
Rapptz

Reputation: 21317

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.

Upvotes: 8

Deduplicator
Deduplicator

Reputation: 45654

  1. You can either wrap them, each for itself, in its own #ifdef:

    #ifndef NO_STATIC_ASSERT
    static_assert(...);
    #endif
    
  2. Or, you can define your own STATIC_ASSERT:

    #ifndef NO_STATIC_ASSERT
        #define STATIC_ASSERT(...) /**/
    #else
      #define STATIC_ASSERT(...) static_assert(__VA_ARGS__)
    #endif
    
    • In practice, #define static_assert(...) works too, though it is UB.
  3. Or, you can just manually remove them.

That way you can remove their influence on compilation-performance (they never had any influence on runtime-performance anyway).

Upvotes: 2

Related Questions