Search⌘ K
AI Features

if constexpr

Explore the if constexpr feature in C++17, which enables compile-time branching for templates. Learn how it discards invalid code paths during compilation to prevent errors and streamline template code. Understand why this feature improves template design and how it differs from regular if statements.

We'll cover the following...

Th​is is a big one! The compile-time if for C++!

The feature allows you to discard branches of an if statement at compile-time based on a constant expression condition.

C++
if constexpr (cond)
statement1; // Discarded if cond is false
else
statement2; // Discarded if cond is true

For Example:

C++
template <typename T>
auto get_value(T t)
{
if constexpr (std::is_pointer_v<T>)
return *t;
else
return t;
}

if constexpr has the potential to simplify a lot of template code - especially when tag dispatching, SFINAE or preprocessor techniques are used.

...