Site Tools


wiki:cpp-sfinae

Table of Contents

C++ SFINAE

SFINAE (Substitution Failure Is Not An Error) is the rule that when template argument substitution produces an invalid type or expression during overload resolution, that candidate is silently removed from consideration rather than causing a compile error.

Use SFINAE with std::enable_if or modern C++20 concepts to write templates that only participate in overload resolution for types satisfying certain properties.

Example

This example shows SFINAE removing invalid template overloads based on type properties.

// compile: g++ -std=c++17 -o sfinae sfinae.cpp
// run: ./sfinae
// description: SFINAE enables/disables template overloads based on type traits
 
#include <iostream>
#include <type_traits>
#include <vector>
 
template <typename T>
typename std::enable_if<std::is_integral_v<T>, void>::type
process(T value) {
    std::cout << "Processing integral: " << value << "\n";
}
 
template <typename T>
typename std::enable_if<std::is_floating_point_v<T>, void>::type
process(T value) {
    std::cout << "Processing float: " << value << "\n";
}
 
int main() {
    process(42);       // calls integral overload
    process(3.14);     // calls floating_point overload
 
    return 0;
}
wiki/cpp-sfinae.md · Last modified: (external edit)