Home > Article > Backend Development > How Does std::enable_if Work with Conditional Return Types and Template Parameters?
Understanding std::enable_if
Understanding std::enable_if requires a grasp of Substitution Failure Is Not An Error.
Definition of std::enable_if
std::enable_if is a specialized template defined as:
<code class="cpp">template<bool Cond, class T = void> struct enable_if {}; template<class T> struct enable_if<true, T> { typedef T type; };</code>
Crucially, the typedef T type definition is only triggered when bool Cond is true.
Usage in Conditional Return Types
Consider the example:
<code class="cpp">template<typename T> typename std::enable_if<std::numeric_limits<T>::is_integer, void>::type foo(const T &bar) { isInt(bar); }</code>
Here, the return type is defined by:
<code class="cpp">std::enable_if<std::numeric_limits<T>::is_integer, void>::type</code>
The usage of enable_if ensures that foo has a valid return type only if is_integer is true for T.
Defaulting the Second Template Parameter
In the example:
<code class="cpp">template<typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0> void foo(const T& bar) { isInt(); }</code>
The second template parameter is defaulted to 0. This allows foo to be called with a single template parameter, e.g. foo
The above is the detailed content of How Does std::enable_if Work with Conditional Return Types and Template Parameters?. For more information, please follow other related articles on the PHP Chinese website!