Skip to content

Static_Assert

DryPerspective edited this page Oct 9, 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_98<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); which can be used to quickly make an assertion. 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.

Features

static_assert_98 A struct with a boolean template parameter, which will fail compilation if that parameter evaluates false
STATIC_ASSERT(...) A macro which expands to an unevaluated instantiation of an unnamed static_assert_98 struct

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