0 day streak
cpp / intermediate
Snippet

Compile-Time Logic Branches

The 'if constexpr' statement allows for conditional compilation. Branches that do not meet the condition are not instantiated by the compiler, which is highly useful for template metaprogramming to avoid compilation errors in branches that wouldn't make sense for certain types.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <type_traits>
template <typename T>
void log_data(T value) {
if constexpr (std::is_floating_point_v<T>) {
std::cout << "Handling float: " << value << "\n";
} else if constexpr (std::is_integral_v<T>) {
std::cout << "Handling integer: " << value << "\n";
} else {
std::cout << "Handling generic type\n";
}
}
int main() {
log_data(3.14); // Compiles only the float branch
log_data(42); // Compiles only the integer branch
return 0;
}
Breakdown
1
if constexpr (std::is_floating_point_v<T>)
The compiler evaluates this at compile-time and discards the other branches.