← Impulso Blog

The benefits of using static assertions in C++

If you're interested in programming in C++, you should learn more about the benefits of the well-known static_assert, or static assertion.

Person using a laptop with headphones around their neck.

Editorial translation by Impulso.

In most programming languages, assertions are often used to detect unexpected or unintended states and situations in a program. An assertion is also a conditional check performed at runtime, though. This means developers need to run that specific piece of code for the assertion to take effect.

But how can this help developers? C++11 introduced static_assert, a compile-time version of assert() that checks conditions during compilation. It also stops compilation if the condition isn't met. This kind of assertion is much more useful for enforcing rules about how code is written in a C++ project. After all, you don't need a runtime test to check the assertion. So let's take a look at the benefits of using static assertions in this versatile language.

Syntax

You can use static_assert at type scope, global scope, or function scope. Below are examples at type scope and function scope.

A static_assert inside struct foo, illustrating an assertion at type scope. A main function checks 2 == 3 with static_assert and supplies the message for a failed assertion.

The second parameter, the message string, is required in C++11 but becomes optional in C++17. When the code is compiled or run with clang, the compiler will report an error with a message like this:

Compiler output identifies the failed static_assert for 2 == 3 and prints the program’s message.

One important difference between static_assert and regular assert() is that the former requires the condition expression to be an integral constant. But what does that mean? Since the condition is asserted at compile time, any such condition can also be evaluated as an integer at compile time. In the example above, 2 == 3 can be evaluated at compile time. The easiest way to test whether something can be an integral constant is to see whether the target object's type declaration can use constexpr. A common example is using a map type as a "constant" lookup table.

Declaration of a const unordered_map containing the pairs 3–3 and 4–4.

The TESTMAP above is static and const, which compiles just fine, but you might run into a problem if you change it to:

C++ declaration attempting to use constexpr with an unordered_map containing the pairs 3–3 and 4–4. The compiler reports that a constexpr variable of type std::unordered_map<int, int> cannot have a non-literal type.

So std:: types such as maps can't be used with static_assert. This also applies when std:: types are used in templates, as shown below.

C++ example iterating over a vector in checkIfContains and using static_assert to test for a value.

This won't compile because checkIfContains, although marked constexpr, uses iterators in the std::vector class that aren't marked constexpr.

That isn't necessarily a bad thing, though, and there are still powerful ways to use static_assert.

Functions

The first practical way to use static_assert is with functions. If a function can be marked constexpr, it can be used in a static_assert:

A constexpr function checks a number in a switch and is called by static_assert with the argument 4.

In the example above, a switch statement checks an integer parameter. The function's return type is constexpr bool. It can be evaluated at compile time because there are no non-literal types or dependencies on runtime state. You can also use functions that declare and operate on local variables.

You can also use more complex functions. Some std:: types meet the requirements for use in a static_assert, such as std::array.

C++ excerpt using a constexpr hash function, two constant arrays and static_assert to compare results.

Functions can also check types instead of integral values. The header introduced in C++11 provides several templates for checking specific type properties or conditions. One example is std::is_same<a, b="">(), which checks whether the two types are the same.

You can combine this with a function template to perform compile-time checks on a type:

Example combining a class hierarchy, a compile-time type test and a static assertion.

Scopes

You can also restrict static_assert to class scope or function scope. This gives you more precise control over where static_assert is evaluated. The ensure_registered_type template applies static_assert to is_registered_type to check its input type.

This template ensures that the assertion is evaluated only in the scope where ensure_registered_type is constructed. Instead of applying the assertion only to a particular file or compilation point in a project, you can use this approach to apply it at several different points, such as in main():

Inside main, decltype supplies a variable’s type to a registration check.

This example uses decyltype to determine the type of a variable and instantiate the ensure_registered_type template with that type.

Want to learn more about this kind of programming?

Then come join our Discord community. We've got developers working with all kinds of tech stacks, so it's the perfect place to share information and professional experiences. We also have job openings, exclusive events, free English classes, and discount codes. And if you ever have a question, you can reach me there at @ine. See you there, okay? To join, just click here.

And hey, we're on WhatsApp too! If you prefer, you can chat with developers there.

[This piece was inspired by and translated from this Medium article]

Related articles