Immediate Context in C 11 SFINAE
The C 11 Standard defines SFINAE (Substitution Failure Is Not An Error) as a technique for conditionally enabling or disabling code based on template argument deduction. Section 14.8.2/8 outlines the conditions for a substitution failure to result in a "hard" compilation error or a "soft" error leading to SFINAE.
The standard refers to an "immediate context" in this section, indicating that only invalid types and expressions in the immediate context of the function type and its template parameter types can cause a deduction failure. However, the definition of "immediate context" is not explicit.
Decision Procedure for Immediate Context
To determine whether a substitution error occurs in the immediate context, consider the following:
Imagine all templates and implicitly-defined functions required for template argument substitution are generated beforehand. Any errors occurring during this preparation are not in the immediate context and will result in hard compilation errors.
If the preparation step completes successfully, any subsequent errors during substitution (e.g., referring to instantiated templates or implicitly-defined functions in the function template signature) do not constitute errors but result in deduction failures.
Examples
Example 1:
template<typename T> void func(typename T::type* arg); template<typename> void func(...); template<typename T> struct A { typedef T* type; }; func<A<int&>>(...);
In this example, instantiating A
Example 2:
template<typename T> void func(typename T::type* arg); template<typename> void func(...); template<typename T> struct A { typedef T* type; }; template<> struct A<char> {}; func<A<char>>(...);
In this example, the preparation step successfully instantiates A
The above is the detailed content of What Defines 'Immediate Context' in C 11 SFINAE?. For more information, please follow other related articles on the PHP Chinese website!