
Static assertions is a feature supported by both BCC32 and the Clang-enhanced C++ compilers. The static_assert keyword is used to test assertions at compile time. This is one of the C++11 features added to BCC32. This keyword operates differently than the macro assert, which raises assertions at run time. The keyword static_assert also differs from the preprocessor directive #error, which operates during preprocessing and simply emits a message.
A static assertion’s declaration is:
1 |
static_assert (constant-expression, error-message); |
The constant-expression must be one that can be statically evaluated as a boolean. If constant-expression is true, the statement does nothing. If false, the compiler generates an error with the text error-message. Because the assertion is tested at compile time, static_assert can do error checking in templates. For instance:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
template <class T, int Size> class Vector { // Compile time assertion to check if // the size of the vector is greater than // 3 or not. If any vector is declared whose // size is less than 4, the assertion will fail static_assert(Size > 3, "Vector size is too small!"); T m_values[Size]; }; int _tmain(int argc, _TCHAR* argv[]) { Vector<int, 4> four; // This will work Vector<short, 2> two; // This will fail return 0; } |
Erroneous static_assert
The constant_expression passed in static_assertion needs to be a valid expression. For example, consider the following code:
1 2 3 4 5 6 |
// demonstrating an erroneous static_assert declaration int main() { static_assert(1 / 0, "never shows up!"); return 0; } |
On compiling above code the C++ Builder compiler flash following error.
static_assert expression is not an integral constant expression
<File name and line number>: division by zero
Find out more about C++ static assertions for Windows development in the Embarcadero DocWiki.
Design. Code. Compile. Deploy.
Start Free Trial Upgrade Today
Free Delphi Community Edition Free C++Builder Community Edition