Could you give an example where static_assert(...)
('C++11') would solve the problem in hand elegantly?
I am familiar with run-time assert(...)
. When should I prefer static_assert(...)
over regular assert(...)
?
Also, in boost
there is something called BOOST_STATIC_ASSERT
, is it the same as static_assert(...)
?
static_assert
is used to make assertions at compile time. When the static assertion fails, the program simply doesn't compile. This is useful in various situations. For example, if you implement some functionality that critically depends on an unsigned int
object having exactly 32 bits. You can add a static_assert
to your code like this:
static_assert(sizeof(unsigned int) * CHAR_BIT == 32);
On platforms with differently sized unsigned int
type, the compilation will fail, drawing attention of the developer to the problematic portion of code.
As another example, you might want to pass an integral value as void*
to a function (a hack, but useful at times) and you want to make sure that the integral value will fit into the pointer:
int i;
static_assert(sizeof(void*) >= sizeof i);
foo((void*)i);
Or you might want to assert that the char
type is signed:
static_assert(CHAR_MIN < 0);
Or that integral division with negative values rounds towards zero:
static_assert(-5 / 2 == -2);
And so on.
Run-time assertions can in many cases be used instead of static assertions, but run-time assertions only work at run time and only when control passes over the assertion. For this reason a failing run-time assertion may lay dormant, undetected for extended periods of time.
Of course, the expression in static assertions has to be a compile-time constant. It can't be a run-time value. For run-time values you have no other choice but use an ordinary assert
.