C++ constexpr static_assert

Introduction

The static_assert directive checks a static (constexpr) condition during compile time.

If the condition is false, the directive fails the compilation and displays an error message.

Example:

int main() 
{ 
    constexpr int x = 123; 
    static_assert(x == 456, "The constexpr value is not 456."); 
} 

Here the static_assert checks if the value of x is equal to 456 during compile time.

Since it is not, the compilation will fail with a "The constexpr value is not 456." message.

We can think of the static_assert as a way of testing our code during compile time.

It is also a neat way of testing if the value of a constexpr expression is what we expect it to be.




PreviousNext

Related