How does if constexpr eliminate branches at compile time?
C++Level: IntermediateCompile-Time Programming
How does if constexpr eliminate branches at compile time?
Hints
- Identify types, object lifetimes and compile-time decisions.
- Separate language guarantees from a particular compiler's behavior.
Answer
constexpr if (C++17)
:Source: src/constexpr/constexpr-if
C++17 introduced if constexpr, which evaluates conditions at compile time
and discards the untaken branch entirely. This is essential for template
metaprogramming because it prevents compilation errors in branches that would
be invalid for certain template instantiations. Unlike regular if, both
branches of a normal if must be valid code even if one is never executed.
#include <iostream>
#include <type_traits>
template <typename T>
auto get_value(T t) {
if constexpr (std::is_pointer_v<T>) {
return *t; // Only compiled when T is a pointer
} else {
return t; // Only compiled when T is not a pointer
}
}
int main() {
int x = 42;
int *p = &x;
std::cout << get_value(x) << "\n"; // Output: 42
std::cout << get_value(p) << "\n"; // Output: 42
}
Source and licence: C/C++ Interview Cheatsheet — Chang Ning Tsai · MIT