The if constexpr Statement
Learn how to use the if constexpr statement in template functions.
We'll cover the following...
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:
Press + to interact
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:
Press + to interact
auto bear = Bear{};speak(bear);
The compiler will then generate a speak()
...