The following example illustrates a basic instance of SFINAE:
Here, attempting to use a non-class type in a qualified name (T::foo) results in a deduction failure for f<int> because int has no nested type named foo, but the program is well-formed because a valid function remains in the set of candidate functions.
Although SFINAE was initially introduced to avoid creating ill-formed programs when unrelated template declarations were visible (e.g., through the inclusion of a header file), many developers later found the behavior useful for compile-time introspection. Specifically, it allows a template to determine certain properties of its template arguments at instantiation time.
For example, SFINAE can be used to determine if a type contains a certain typedef:
When T has the nested type foobar defined, the instantiation of the first test works and the null pointer constant is successfully passed. (And the resulting type of the expression is yes.) If it does not work, the only available function is the second test, and the resulting type of the expression is no. An ellipsis is used not only because it will accept any argument, but also because its conversion rank is lowest, so a call to the first function will be preferred if it is possible; this removes ambiguity.
In C++11, the above code could be simplified to:
With the standardisation of the detection idiom in the Library fundamental v2 (n4562) proposal, the above code could be re-written as follows:
The developers of Boost used SFINAE in boost::enable_if3 and in other ways.
Vandevoorde, David; Nicolai M. Josuttis (2002). C++ Templates: The Complete Guide. Addison-Wesley Professional. ISBN 0-201-73484-2. 0-201-73484-2 ↩
International Organization for Standardization. "ISO/IEC 14882:2003, Programming languages – C++", § 14.8.2. ↩
Boost Enable If http://www.boost.org/doc/libs/release/libs/utility/enable_if.html ↩