0 day streak
cpp / intermediate
Snippet

Static Template Branching with Constexpr If

The 'if constexpr' statement allows for compile-time branching. The branch not taken is discarded by the compiler, which is essential for template metaprogramming to avoid instantiating invalid code for certain types.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <type_traits>
template <typename T>
void process_value(T val) {
if constexpr (std::is_floating_point_v<T>) {
std::cout << "Processing float: " << val << std::endl;
} else {
std::cout << "Processing non-float value" << std::endl;
}
}
int main() {
process_value(3.14); // Branches at compile-time
process_value(42); // Discards the float branch
return 0;
}
Breakdown
1
if constexpr (std::is_floating_point_v<T>)
Evaluates the condition at compile-time based on the template type.
2
std::cout << "Processing float: " << val << std::endl;
This line is only compiled into the binary if T is a floating-point type.