C’s assert library is a useful tool for catching invalid invariants (conditions that must hold true in order for your system to operate as specified) in your program. The big problem with assert is that it’s a run-time check; in many cases the best you can do to recover from an assert failure is restart the system or put it into a quiescent state.
In a lot of cases the (faulty) invariants could be detected at compile-time but in C++98 there was no mechanism for doing so. The pre-processor has an assert-like mechanism – #error – but the pre-processor has no knowledge of your C++ code so it cannot evaluate program invariants.
In C++11 a compile-time assert mechanism was added: static_assert.
static_assert acts like run-time assert except that the checked-condition must be a constant-expression (that is, an expression that can be evaluated at compile-time); the checked-condition must be a boolean expression, or an expression that can be converted to a boolean.
The message string must be a string literal. It cannot be a (compile-time) computed value (ignoring pre-processor stringification).
From C++17 the message will be optional.
Can’t wait? Download the full set of articles as a PDF, here.
To learn more about Feabhas’ Modern C++ training courses, click here.