Search⌘ K

The if constexpr Statement

Explore how to use the if constexpr statement in C++ template functions to enable compile-time branching based on type traits. Understand how this feature helps generate type-specific code without compilation errors and aids in implementing compile-time polymorphism effectively.

if constexpr in template functions

The if constexpr statement allows template functions to evaluate different scopes in the same function at compile time. Take a look at the following example, where a function template called speak() tries to differentiate member functions depending on the type:

C++
struct Bear {
auto roar() const { std::cout << "roar\n"; }
};
struct Duck {
auto quack() const { std::cout << "quack\n"; }
};
template <typename Animal>
auto speak(const Animal& a) {
if (std::is_same_v<Animal, Bear>) {
a.roar();
} else if (std::is_same_v<Animal, Duck>) {
a.quack();
}
}

Let’s say we compile the following lines:

C++
auto bear = Bear{};
speak(bear);

The compiler will then generate a speak() ...