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

前端 未结 2 1299
忘掉有多难
忘掉有多难 2021-01-14 01:11

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 
typename std::en         


        
相关标签:
2条回答
  • 2021-01-14 01:32

    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.

    0 讨论(0)
  • 2021-01-14 01:44

    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);
    }
    
    0 讨论(0)
提交回复
热议问题