Substitution failure is not an error: Difference between revisions

Content deleted Content added
mNo edit summary
No edit summary
 
(48 intermediate revisions by 40 users not shown)
Line 1:
{{Short description|C++ programming technique}}
'''Substitution failure is not an error''' ('''SFINAE''') refers to a situation in [[C++]] where an invalid substitution of [[template (programming)|template]] parameters is not in itself an error. David Vandevoorde first introduced the acronym SFINAE to describe related programming techniques.<ref>{{cite book | last=Vandevoorde | first=David | coauthors=Nicolai M. Josuttis | title=C++ Templates: The Complete Guide | publisher=Addison-Wesley Professional | year=2002 | isbn=0-201-73484-2}}</ref>
{{Use dmy dates|date=December 2023}}
'''Substitution failure is not an error''' ('''SFINAE''') refers tois a situationprinciple in [[C++]] where an invalid substitution of [[templateTemplate (programmingC++)|template]] parameters is not in itself an error. David Vandevoorde first introduced the acronym SFINAE to describe related programming techniques.<ref>{{cite book | last=Vandevoorde | first=David | coauthorsauthor2=Nicolai M. Josuttis | title=C++ Templates: The Complete Guide | publisher=Addison-Wesley Professional | year=2002 | isbn=0-201-73484-2}}</ref>
 
Specifically, when creating a candidate set for [[overload resolution]], some (or all) candidates of that set may be the result of substitutinginstantiated templates with (potentially deduced) template arguments substituted for the corresponding template parameters. If an error occurs during the substitution of a set of arguments for any given template, the compiler removes the potential overload from the candidate set instead of stopping with a compilation error, provided the substitution error is onethat the C++ standard grantspermits discarding such treatmenta substitution error as mentioned.<ref>International Organization for Standardization. "ISO/IEC 14882:2003, Programming languages &mdash; C++", § 14.8.2.</ref> If one or more candidates remain and overload resolution succeeds, the invocation is well-formed.
 
==Example==
The following example illustrates a basic instance of SFINAE:
 
<sourcesyntaxhighlight lang="cpp">
struct Test {
typedef int typefoo;
};
 
template <typename T>
void f(typename T::typefoo) {} // Definition #1
 
template <typename T>
void f(T) {} // Definition #2
 
int main() {
f<Test>(10); // Call #1.
f<int>(10); // Call #2. Without error thanks(even tothough SFINAE.there is no int::foo)
// thanks to SFINAE.
return 0;
}
</syntaxhighlight>
</source>
 
Here, attempting to use a non-class type in a qualified name (<code>T::typefoo</code>) results in a deduction failure for <code>f<int></code> because <code>int</code> has no nested type named <code>typefoo</code>, 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:
 
<sourcesyntaxhighlight lang="cpp">
#include <iostream>
 
template <typename T>
struct has_typedef_typeHasTypedefFoobar {
// VariablesTypes "yes" and "no" are guaranteed to have different sizes,
// specifically sizeof(yes) == 1 and sizeof(no) == 2.
typedef char yes[1];
typedef char no[2];
 
template <typename C>
static yes& test(typename C::typefoobar*);
 
template <typename>
static no& test(...);
 
// If the "sizeof" of the result of calling test<T>(0nullptr) would beis equal to the sizeof(yes),
// sizeof(yes), the first overload worked and T has a nested type named type.
// foobar.
static const bool value = sizeof(test<T>(0nullptr)) == sizeof(yes);
};
 
struct fooFoo {
typedef float typefoobar;
};
 
int main() {
std::cout << std::boolalpha;
std::cout << has_typedef_typeHasTypedefFoobar<int>::value << std::endl; // Prints false
std::cout << has_typedef_typeHasTypedefFoobar<fooFoo>::value << std::endl; // Prints true
return 0;
}
</syntaxhighlight>
</source>
 
When <code>T</code> has the nested type <code>typefoobar</code> defined, the instantiation of the first <code>test</code> works and 0 is successfully passed as the null pointer constant is successfully passed. (And the resulting type of the expression is <code>yes</code>.) If it does not work, the only available function is the second <code>test</code>, and the resulting type of the expression is <code>no</code>. (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.)
 
== C++11 simplification ==
Developers of [[Boost C++ Libraries|Boost]] used SFINAE to great effect in boost::enable_if<ref name="enable_if">[http://www.boost.org/doc/libs/release/libs/utility/enable_if.html Boost Enable If]</ref> and in other ways.
In [[C++11]], the above code could be simplified to:
 
<syntaxhighlight lang="cpp">
#include <iostream>
#include <type_traits>
 
template <typename T, typename = void>
struct HasTypedefFoobar : std::false_type {};
 
template <typename T>
struct HasTypedefFoobar<T, std::void_t<typename T::foobar>> : std::true_type {};
 
struct Foo {
using foobar = float;
};
 
int main() {
std::cout << std::boolalpha;
std::cout << HasTypedefFoobar<int>::value << std::endl;
std::cout << HasTypedefFoobar<Foo>::value << std::endl;
return 0;
}
</syntaxhighlight>
 
With the standardisation of the detection idiom in the [http://en.cppreference.com/w/cpp/experimental/lib_extensions_2 Library fundamental v2 (n4562)] proposal, the above code could be re-written as follows:
<syntaxhighlight lang="cpp">
#include <iostream>
#include <type_traits>
 
template <typename T>
using HasTypedefFoobarUnderlying = typename T::foobar;
 
struct Foo {
using foobar = float;
};
 
int main() {
std::cout << std::boolalpha;
std::cout << std::is_detected<HasTypedefFoobarUnderlying, int>::value << std::endl;
std::cout << std::is_detected<HasTypedefFoobarUnderlying, Foo>::value << std::endl;
return 0;
}
</syntaxhighlight>
 
DevelopersThe developers of [[Boost C++ Libraries|Boost]] used SFINAE to great effect in boost::enable_if<ref name="enable_if">[http://www.boost.org/doc/libs/release/libs/utility/enable_if.html Boost Enable If]</ref> and in other ways.
 
==References==
{{reflist}}
 
{{C++ programming language}}
 
[[Category:C++]]
[[Category:Articles with example C++ code]]
[[Category:Software design patterns]]