Substitution failure is not an error

From Wikipedia, the free encyclopedia

Substitution failure is not an error (SFINAE) is a principle in the C++ programming language, used when resolving overloaded functions or templates. SFINAE states that when substituting types in overload resolution, a failure to substitute a particular type is not an error so long as there are further, less preferred overloads available [1].

For example, consider a template function f<T>(), which should be applicable to all types except int. Using SFINAE, the function can be declared thus:

template<typename T> struct can_use_f {
        typedef void type;
};

template<> struct can_use_f<int> {
};

template<typename T>
typename can_use_f<T>::type
f(T const &);

int main()
{
        f(1);
        f(1.);
}

Overload resolution will fail for f(int), because can_use_f<int>::type is not defined. On the other hand, for other types can_use_f<T>::type is void, the desired return type of f(), and instantition proceeds normally. (This template is a common idiom, implemented in C++ metaprogramming libraries such as Boost as "enable_if" and "disable_if").

SFINAE is usually used to confine template arguments to types with specific properties, or to instantiate a template differently based upon the type or value of another template.