std :: enable_if的第二个参数的用途是什么? [英] What's the use of second parameter of std::enable_if?

查看:282
本文介绍了std :: enable_if的第二个参数的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对std :: enable_if的第二个参数感到困惑。
在使用返回类型的int,我们可以使用:

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

但是如何在参数或模板中使用enable_if?在这种情况下,以下函数的区别是什么:

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

谢谢。

推荐答案

这意味着

template<class T , 
   class = typename std::enable_if<std::is_integral<T>::value>::type >

会变成

template<class T , 
   class = void >



true ,因此该函数允许用于 T ,因此参与重载分辨率。

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.

如果条件不满足,它将变为非法,并且 typename std :: enable_if< ...> :: type 使类型 T 的函数无效。在你的例子中,第一个方法允许所有的整数类型( int unsigned / code>,...),但没有类等。

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.

第二个 int 你的示例中的唯一版本会丢失一些信息,并将值从unsigned转换为signed或缩小一些值,这就是为什么第一个版本在某些情况下真的有用。

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.

请注意, void 实际上是 std :: enable_if 的第二个参数的默认值,它通常足以启用或禁用模板等,因为你不需要一个特定的类型。所有你需要知道/检测的是,无论它是否有效( void )或无效,在这种情况下没有有效的替换 :: type 部分。

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.

这篇关于std :: enable_if的第二个参数的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆