Home >Backend Development >C++ >How Does SFINAE Differ When Applied to Return Types Versus Template Parameters?
SFINAE Applicability in Return Types vs. Template Parameters
In C programming, SFINAE (Substitution Failure Is Not An Error) is a technique for template metaprogramming. SFINAE allows you to use template parameters to specify constraints on the type of arguments that can be passed to a template function or class.
In your example, you have two implementations of a function named foo:
template<typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type> auto foo(T) -> void; template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type> auto foo(T) -> void;
The first implementation uses SFINAE with the std::enable_if metafunction in the template parameters. This means that the template function foo can only be called with types that satisfy the condition std::is_integral
The second implementation, however, uses SFINAE with std::enable_if in the return type of the template function. In this case, the function foo can be called with any type, but the return type will be of type void only if T satisfies the condition std::is_integral
In your example, the first implementation fails to compile because the default template argument for the second template parameter is not taken into account when determining if the template is already instantiated for the first template parameter. Thus, the compiler assumes you are attempting to redeclare the same function template twice, resulting in the error.
On the other hand, the second implementation works because the expression typename std::enable_if
The above is the detailed content of How Does SFINAE Differ When Applied to Return Types Versus Template Parameters?. For more information, please follow other related articles on the PHP Chinese website!