0 day streak
cpp / expert
Snippet

Conditional Template Logic via Constexpr If

Enabling selective compilation of code paths based on type traits. Unlike standard if, constexpr if discards the non-taken branch during compilation.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <type_traits>
template <typename T>
auto compute(T val) {
if constexpr (std::is_pointer_v<T>) {
return *val;
} else {
return val;
}
}
// Usage:
int x = 10;
auto r1 = compute(x); // returns int
auto r2 = compute(&x); // returns int
Breakdown
1
if constexpr (std::is_pointer_v<T>)
Evaluates the condition at compile-time; the false branch is not instantiated.
2
std::is_pointer_v<T>
A type trait that checks if the template argument is a pointer type.
3
return *val;
Only compiled if T is a pointer, preventing errors for non-pointer types.