Substitution failure is not an error: Difference between revisions

Content deleted Content added
mNo edit summary
No edit summary
 
(One intermediate revision by one other user not shown)
Line 3:
'''Substitution failure is not an error''' ('''SFINAE''') is a principle in [[C++]] where an invalid substitution of [[Template (C++)|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 |author2=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 instantiated 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 that the C++ standard permits discarding thesuch a substitution error as mentioned.<ref>International Organization for Standardization. "ISO/IEC 14882:2003, Programming languages – C++", § 14.8.2.</ref> If one or more candidates remain and overload resolution succeeds, the invocation is well-formed.
 
==Example==
Line 37:
 
template <typename T>
struct has_typedef_foobarHasTypedefFoobar {
// Types "yes" and "no" are guaranteed to have different sizes,
// specifically sizeof(yes) == 1 and sizeof(no) == 2.
Line 55:
};
 
struct fooFoo {
typedef float foobar;
};
Line 61:
int main() {
std::cout << std::boolalpha;
std::cout << has_typedef_foobarHasTypedefFoobar<int>::value << std::endl; // Prints false
std::cout << has_typedef_foobarHasTypedefFoobar<fooFoo>::value << std::endl; // Prints true
return 0;
}
Line 75:
#include <iostream>
#include <type_traits>
 
template <typename... Ts>
using void_t = void;
 
template <typename T, typename = void>
struct has_typedef_foobarHasTypedefFoobar : std::false_type {};
 
template <typename T>
struct has_typedef_foobarHasTypedefFoobar<T, std::void_t<typename T::foobar>> : std::true_type {};
 
struct fooFoo {
using foobar = float;
};
Line 91 ⟶ 88:
int main() {
std::cout << std::boolalpha;
std::cout << has_typedef_foobarHasTypedefFoobar<int>::value << std::endl;
std::cout << has_typedef_foobarHasTypedefFoobar<fooFoo>::value << std::endl;
return 0;
}
Line 103 ⟶ 100:
 
template <typename T>
using has_typedef_foobar_tHasTypedefFoobarUnderlying = typename T::foobar;
 
struct fooFoo {
using foobar = float;
};
Line 111 ⟶ 108:
int main() {
std::cout << std::boolalpha;
std::cout << std::is_detected<has_typedef_foobar_tHasTypedefFoobarUnderlying, int>::value << std::endl;
std::cout << std::is_detected<has_typedef_foobar_tHasTypedefFoobarUnderlying, fooFoo>::value << std::endl;
return 0;
}