c++ - Understanding SFINAE -
as far know, sfinae means substitution failures not result in compilation errors, remove prototype list of possible overloads.
what not understand: why sfinae:
template <bool c, typename t = void> struct enable_if{}; template <typename t> struct enable_if<true, t> { typedef t type; };
but not?
template <bool c> struct assert; template <> struct assert<true>{};
from understanding, underlying logic identical here. question emerged comments this answer.
in c++98, sfinae done either return type or function's dummy argument default parameter
// sfinae on return type functions fixed arguments (e.g. operator overloading) template<class t> typename std::enable_if< std::is_integral<t>::value, void>::type my_function(t const&); // sfinae on dummy argument default parameter functions no return type (e.g. constructors) template<class t> void my_function(t const&, std::enable_if< std::is_integral<t>::value, void>::type* = nullptr);
in both cases, substution of t
in order nested type type
essence of sfinae. in contrast std::enable_if
, assert
template not have nested type can used in substitution part of sfinae.
see jonathan wakely's excellent accu 2013 presentation more details , c++11 expression sfinae. among others (as pointed out @bartekbanachewicz in comments) is possible use sfinae in function template default arguments
// use c++11 default function arguments, no clutter in function's signature! template<class t, class dummy = typename std::enable_if< std::is_integral<t>::value, void>::type> void my_function(t const&);
Comments
Post a Comment