4

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

template <class T>
typename std::enable_if<mpi::is_builtin<T>::value, int>::type
foo() { return 1; }

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

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

谢谢。

4

2 回答 2

3

这意味着如果发生

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

它成为了

template<class T , 
   class = void >

如果条件std::is_integral<T>::valuetrue,则该函数被允许用于该类型T,因此参与重载决议。

如果不满足条件,则它变为非法,并且typename std::enable_if<...>::type使该类型的函数无效T。在您的示例中,第一种方法允许所有整数类型(int, unsigned, long, ...),但不允许类等。

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.

于 2013-09-24T09:40:39.073 回答
0

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);
}
于 2013-09-24T15:28:35.190 回答