SFINAE

Substitution Failure Is Not An Error

Interview Relevant: Template metaprogramming

SFINAE

Template substitution failures don't cause errors.

Code Examples

SFINAE for compile-time type selection.

cpp
1#include <type_traits>
2
3// enable_if for conditional template
4template<typename T>
5typename enable_if<is_integral<T>::value, T>::type
6process(T value) {
7    return value * 2;  // Only for integral types
8}
9
10template<typename T>
11typename enable_if<is_floating_point<T>::value, T>::type
12process(T value) {
13    return value / 2;  // Only for floating types
14}
15
16// C++17 if constexpr (simpler alternative)
17template<typename T>
18auto processModern(T value) {
19    if constexpr (is_integral_v<T>) {
20        return value * 2;
21    } else if constexpr (is_floating_point_v<T>) {
22        return value / 2;
23    }
24}
25
26// void_t for detection idiom
27template<typename, typename = void>
28struct has_size : false_type {};
29
30template<typename T>
31struct has_size<T, void_t<decltype(declval<T>().size())>> : true_type {};
32
33static_assert(has_size<vector<int>>::value);  // true
34static_assert(!has_size<int>::value);         // true

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In