static_assert
Runtime assertions have been a staple of C++ code reliability since the beginning of time. However, there's often been a disagreement over whether or not to leave the assertions in production code, because they inherently slow things down.
The modern answer to this conundrum is the C++ “static_assert” directive.
This is like a runtime assertion, but it is fully evaluated at compile-time,
so it's super-fast.
Failure of the assertion triggers a compile-time error, preventing execution,
and the code completely disappears at run-time.
Unfortunately, there really aren't that many things you can assert at compile-time.
Most computations are dynamic and stored in variables at runtime.
However, the static_assert statement can be useful for things like
blocking inappropriate use of template instantiation code,
or for portability checking such as:
static_assert(sizeof(float) == 4, "float is not 32 bits");
This statement is an elegant and language-standardized method to prevent compilation on a platform where a “float” data type is 64-bits,
alerting you to a portability problem.