static_assert
Overview
static_assert
provides a way to check if a condition is true at compile-time, if false,
compilation stops with error message. ESTD_STATIC_ASSERT
and ESTD_STATIC_ASSERT_MESSAGE
are the functions defined in the static_assert.h header, which perform static assertion and
depending on the condition, they display fixed and user-defined error messages respectively.
Usage
The usage constraint applicable for static_assert is provided below:
Constraint |
The static_assert is only a compilation check and will not impact run time. |
Example
The following code shows a simple example of the usage of ESTD_STATIC_ASSERT
:
TEST(Assert, ZeroLength)
{
// Compilation stops with error message ESTD_STATIC_ASSERT, if the array is created with size 0.
::estd::array<int32_t, 4> zeroLengthArray{};
ESTD_STATIC_ASSERT(zeroLengthArray.size() > 0);
}
The below code shows a simple example of the usage of ESTD_STATIC_ASSERT_MESSAGE
:
TEST(AssertMessage, ZeroLength)
{
// If the array is created with size 0, compilation stops with error message provided as
// argument.
::estd::array<int32_t, 3> zeroLengthArray{};
ESTD_STATIC_ASSERT_MESSAGE(zeroLengthArray.size() > 0, "Zero sized array should be avoided");
}