capypad
0 day streak
cpp / expert
Snippet

SFINAE with std::enable_if

Substitution Failure Is Not An Error (SFINAE) allows the compiler to discard template overloads that would result in invalid code. std::enable_if_t leverages this to enable a function only when a specific compile-time condition (like being an integer) is met.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
template <typename T>
std::enable_if_t<std::is_integral_v<T>, T>
increment(T value) {
return value + 1;
}
 
// Usage:
// auto a = increment(5); // Compiles
// auto b = increment(3.14); // Compiler Error
Breakdown
1
std::enable_if_t<std::is_integral_v<T>, T>
Evaluates the condition; if true, the type is T; if false, this overload is discarded.
2
std::is_integral_v<T>
A type trait that checks if T is a built-in integral type.