What is the use of the second parameter std :: enable_if?

I got confused in the second parameter of std :: enable_if. When using the return type int, we can use it:

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 a parameter or template? In this case, what's the difference 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; }

Thank.

+1
source share
2 answers

This means that in the case of

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

he becomes

template<class T , 
   class = void >

if the condition std::is_integral<T>::valueis equal true, therefore the function is allowed for the type Tand therefore is involved in overload resolution.

, , typename std::enable_if<...>::type T. (int, unsigned, long,...), ..

int -only unsigned , .

, void std::enable_if, .., . , /, , (void) , ::type.

+3

:

, CopyConstructible, enable_if :

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

Source: https://habr.com/ru/post/1543087/


All Articles