Search code examples
c++templatesgenericsc++11enable-if

What's the use of second parameter of std::enable_if?


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 <class T>
typename std::enable_if<mpi::is_builtin<T>::value, int>::type
foo() { return 1; }

But how can I use enable_if in paramter or template? In this case, what's the difference of too functions below:

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; }

Thanks.


Solution

  • 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.