Home >Backend Development >C++ >What Constitutes the 'Immediate Context' in C 11 SFINAE?

What Constitutes the 'Immediate Context' in C 11 SFINAE?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-10 18:12:11798browse

What Constitutes the

What Exactly Is the "Immediate Context" in C 11 SFINAE?

The concept of "immediate context" is crucial in C 11's Substitution Failure Is Not an Error (SFINAE) idiom. According to the C 11 Standard, only invalid types and expressions "in the immediate context" of the function type and its template parameter types can result in a deduction failure.

Initial Understanding

The Standard provides a limited hint in a note: "evaluation of substituted types and expressions can result in side effects such as class template specializations, function template specializations, implicit function generation, etc." These side effects are not considered part of the "immediate context."

Decision Procedure

To determine whether a substitution error occurs in the "immediate context," follow this procedure:

  1. Identify Necessary Templates and Functions: Consider all templates and implicitly-defined functions required for argument substitution.
  2. Pre-Instantiation Step: Imagine generating these templates and functions before substitution.
  3. Direct Errors: If any errors occur during this pre-instantiation step, they are not in the immediate context and result in hard compilation errors.
  4. Deduction Failure: If pre-instantiation succeeds, any subsequent errors during substitution are not errors but result in deduction failures.

Concrete Examples

  • Example 1 (Hard Error):
template<typename T>
void func(typename T::type* arg);
func<A<int&>&>(nullptr); // T::type* is invalid, causing a hard error.
  • Example 2 (Deduction Failure):
template<typename T>
void func(typename T::type* arg);
template<>
struct A<char> {};
func<A<char>>(nullptr); // T::type* is not defined, leading to a deduction failure.

Conclusion

The "immediate context" refers to expressions and types that can be resolved without requiring additional template or function generation beyond the necessary pre-instantiation step. Errors occurring in this pre-instantiation stage result in hard compilation errors, while errors in the subsequent substitution stage cause deduction failures.

The above is the detailed content of What Constitutes the 'Immediate Context' in C 11 SFINAE?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn