static(if), static(assert) and Type Traits

The use of static(if) and static(assert) in conditional compilation is explained in this lesson.

We'll cover the following

static if

static if is the compile time equivalent of the if statement.

Just like the if statement, static if takes a logical expression and evaluates it. Unlike the if statement, static if is not about execution flow; rather, it determines whether a piece of code should be included in the program or not.

The logical expression must be evaluable at compile time. If the logical expression evaluates to true, the code inside the static if gets compiled. If the condition is false, the code is not included in the program as if it has never been written. The logical expressions commonly take advantage of the is expression and __ traits.

static if can appear at module scope or inside definitions of struct, class, template, etc. Optionally, there may be else clauses as well.

Let’s use static if with a simple template, making use of the is expression. We will see other examples of static if in the next chapter:

Get hands-on with 1200+ tech skills courses.