I am confused about the second parameter of std::enable_if. In using of a return type of int, we can make it using:
template
typename std::en
It means that in case of
template<class T ,
class = typename std::enable_if<std::is_integral<T>::value>::type >
it becomes
template<class T ,
class = void >
if the condition std::is_integral<T>::value
is true
, hence the function is allowed for the type T
and therefore participates in overload resolution.
If the condition is not met, it becomes illegal and the typename std::enable_if<...>::type
invalidates the function for the type T
. In your example, the first method allows all integral types (int
, unsigned
, long
, ...) but no classes, etc.
The second, int
-only version in your example would loose some information and convert values from unsigned to signed or narrow some values, which is why the first version can be really helpful in some cases.
Note that void
is actually the default for the second parameter of std::enable_if
, which is often sufficient to enable or disable templates, etc. as you don't really need a specific type. All you need to know/detect is, whether or not it is valid (void
) or invalid, in which case there is no valid substitution for the ::type
part.
what's the difference of too functions below:
One is a template that can be called for any CopyConstructible type, the enable_if
only constrains it when the default template argument is used:
#include <iostream>
template<class T ,
class = typename std::enable_if<std::is_integral<T>::value>::type >
T too(T t) { std::cout << "here" << std::endl; return t; }
int too(int t) { std::cout << "there" << std::endl; return t; }
int main()
{
too<double, void>(1.0);
}