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

∥☆過路亽.° 提交于 2019-12-02 04:44:57

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/18977799/whats-the-use-of-second-parameter-of-stdenable-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!