Skip to content

Static_Assert

DryPerspective edited this page Sep 22, 2023 · 8 revisions

A C++98 analogue to validate assumptions at compile time. As static_assert is a keyword in C++11, we need to use a different approach here, and take special care not risk colliding with that keyword. This is achieved through a simple but effective templated class, dp::static_assert_98. Creating or inheriting from an instance of dp::static_assert<condition> will succeed if condition is true, but will cause a compilation failure if condition is false.

This header also includes a macro, STATIC_ASSERT(condition); equivalent to creating an instance of dp::static_assert. This macro will not be activated if some other header also defines a macro STATIC_ASSERT, and can be suppressed entirely by defining DP_NO_ASSERT_MACRO.

No other headers in the library include this one directly, so the macro will only be present if the user includes "cpp98/static_assert.h" in their code, and does not suppress it with DP_NO_ASSERT_MACRO. Those concerned about possible name pollution due to this file being included internally can rest easy.

Sample code

#include "cpp98/static_assert.h"

int main(){
   //Require that int types are four bytes
   STATIC_ASSERT(sizeof(int) == 4);
}

Clone this wiki locally