Substitution failure is not an error
From Wikipedia, the free encyclopedia
Substitution failure is not an error (SFINAE) refers to a situation in C++ where an invalid substitution of template parameters is not in itself an error. The acronym SFINAE was first introduced by David Vandevoorde to describe related programming techniques.[1]
Specifically, when creating a candidate set for overload resolution, some (or all) candidates of that set may be the result of substituting template parameters with deduced template arguments. If during substitution an error occurs, the potential candidate is just dropped from the candidate set (instead of making the program erroneous outright) provided the substitution error is recognized for that treatment by the C++ standard.[2] If one or more candidates remain and overload resolution succeeds, the program may be well-formed.
The following example illustrates a basic instance of SFINAE:
struct Test { typedef int Type; }; template < typename T > void f( typename T::Type ) {} // definition #1 template < typename T > void f( T ) {} // definition #2 f< Test > ( 10 ); //call #1 f< int > ( 10 ); //call #2 without error thanks to SFINAE
Here, with SFINAE, call #2 will not produce an error because definition #1 is just skipped by the compiler.
Although SFINAE as a language behavior was designed to avoid programs becoming ill-formed because unrelated template declarations were visible (e.g., through the inclusion of a header file), it was found to be a useful means for compile-time introspection. Specifically, it allows a template to determine certain properties of its template arguments at instantiation time.
[edit] References
- ^ Vandevoorde, David; Nicolai M. Josuttis (2002). C++ Templates: The Complete Guide. Addison-Wesley Professional. ISBN 0-201-73484-2.
- ^ International Standardization Organization. "ISO/IEC 14882:2003, Programming languages — C++", § 14.8.2.