constexpr if
- C++ course
- Expert
- Lesson 9/47
- 5 min
Learn compile-time branching with constexpr if.
constexpr if
if constexpr (C++17) is a condition evaluated at compile time. When the condition is false, that branch is not compiled; it is discarded entirely. Example: if constexpr (std::is_integral_v<T>) return v + 1; else return v;.
A regular if compiles both branches and chooses at run time; if constexpr compiles only the matching branch. In templates this prevents the unsupported branch from causing a compile error.
Discarded branch is not compiled
Inside a template, if you do not use if constexpr, every branch is compiled for all types. If a branch calls v.size() but v is an int, you get a compile error.
With if constexpr the discarded branch is not compiled, so the error never arises. The compiler processes only the chosen branch; a single template can safely support different types.
Practice Write a template with if constexpr
Write template <typename T> auto increment(T v). In the body, use if constexpr (std::is_integral_v<T>) { return v + 1; } else { return v; }. In main write std::cout << increment(7);.
Starter code
#include <iostream>
#include <type_traits>
// Define the increment template here
int main() {
// Print the result
return 0;
}Sample solution
#include <iostream>
#include <type_traits>
template <typename T>
auto increment(T v) {
if constexpr (std::is_integral_v<T>) {
return v + 1;
} else {
return v;
}
}
int main() {
std::cout << increment(7);
return 0;
}Expected output
8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each piece to its role
| Term | Meaning |
|---|---|
if constexpr |
Compile-time branch |
if (cond) |
Run-time branch |
std::is_integral_v |
Type check |
else |
Alternative branch |
2 Complete the condition
if constexpr (std::is_integral_v<____>) { return v + 1; } else { return v; }
if constexpr (std::is_integral_v<T>) { return v + 1; } else { return v; }
Explanation: std::is_integral_v<T> checks whether T is an integral type.
3 What does if constexpr do that regular if does not?
if constexpr (cond) { ... } else { ... }- Runs faster
- Does not compile the discarded branch Correct answer
- Only works with int
- Cannot be used outside templates
Explanation: if constexpr discards the false branch at compile time.