SFINAE (Substitution Failure Is Not An Error)


What is SFINAE?

SFINAE (“Substitution Failure Is Not An Error”)  is a C++ feature that is linked to templates and argument deductions. (during the template argument substitution phase).

It refers to the fact that, in case the compiler tries to match a data type and fails, it will not raise an error, but instead will ignore that substitution and try to find a better one. If no valid substitution is found, the error will be thrown.

 

Compiler work: function matching

How does the compiler match the correct function?

 

Regular functions

  1. Name lookup (detecting the functions that are available)
    • test(int)
    • test(string)
  2. Overload resolution
    • Detects the best viable functions => test(int) in our case

Template functions

  1. Name lookup
  2. Template argument substitution #1
  3. Template argument deduction
  4. Template argument substitution #2
  5. Overload resolution
    • No compiler error at this point!

 

sfinae

You can see that the substitution is performed twice.

That is because the argument deduction cannot be done before an initial pass on the templates, in order to substitute the specified arguments, and  the deduced argument are dependent on the argument deduction itself.

CPPReference Explanation

Function template parameters are substituted (replaced by template arguments) twice:

  • explicitly specified template arguments are substituted before template argument deduction
  • deduced arguments and the arguments obtained from the defaults are substituted after template argument deduction

Substitution occurs in

  • all types used in the function type (which includes return type and the types of all parameters)
  • all types used in the template parameter declarations
  • all expressions used in the function type (since C++11)
  • all expressions used in a template parameter declaration (since C++11)

substitution failure is any situation when the type or expression above would be ill-formed (with a required diagnostic), if written using the substituted arguments.

Leave a comment

Your email address will not be published.