Home >Backend Development >C++ >SFINAE in C : Template Parameter vs. Return Type – What's the Difference?

SFINAE in C : Template Parameter vs. Return Type – What's the Difference?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-14 05:53:171002browse

SFINAE in C  : Template Parameter vs. Return Type – What's the Difference?

SFINAE in Return Type vs Template Parameter: A Comparison

In C , the Substitution Failure Is Not An Error (SFINAE) idiom allows conditional compilation based on the availability of types. However, its behavior can vary when placed in different positions within a template.

SFINAE in Template Parameter

In the code below, SFINAE is used as a template parameter to enable or disable a particular template function overload.

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 { /* ... */ }

In this case, SFINAE is applied to the second template parameter, which is effectively a placeholder. The error occurs when attempting to call foo(3.4) because the second template function declaration with std::enable_if::value> is not defined, resulting in a missing overload.

SFINAE in Return Type

In contrast, the following code uses SFINAE in the return type:

template<typename T>
auto foo(T) -> typename std::enable_if<std::is_integral<T>::value>::type { /* ... */ }

template<typename T>
auto foo(T) -> typename std::enable_if<std::is_floating_point<T>::value>::type { /* ... */ }

In this case, SFINAE is applied to the return type, which allows the compiler to differentiate between the two template functions based on the provided argument type.

Why the Difference?

The difference in behavior stems from the use of default template arguments. In the first example, the second template parameter is defaulted to typename std::enable_if::value>::type, which makes the template function declarations equivalent.

However, in the second example, the return type uses SFINAE within an expression, which is part of the function signature. This ensures that the template functions have different signatures and allows SFINAE to work as expected.

The above is the detailed content of SFINAE in C : Template Parameter vs. Return Type – What's the Difference?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn