Search code examples
c++type-deduction

Template type deduction


I have come across class = std::enbale_if<condition, type>::type couple times in template parameter list, I know what std::enable_if<B,T>::type does but not sure what class = does ? I mean I know class type_name = type but why there is no type name in class = ? when would I use it ?

Edit: This example from here

template <class T, class U, class = typename enable_if
          <is_lvalue_reference<T>::value ? is_lvalue_reference<U>::value : true>::type>
inline T&& forward(U&& u)
{
    return static_cast<T&&>(u);
}

Solution

  • This is SFINAE (substitution failure is not an error). Below are two examples, where constraints are put on struct and class to disallow instantiations with types that would not be correct.

    but not sure what class = does ? I mean I know class type_name = type but why there is no type name in class = ? when would I use it ?

    This is an unnamed template parameter type, you could give it a name but its not needed as this parameter is only used during overload resoultion (to remove non valid candidates). Actually giving it a name might show warnings.

    http://coliru.stacked-crooked.com/a/25162a3eb107943f

    // Allow only T to be floating type (!! actually static_assert would be preferred here)
    template<class T,
             class = typename std::enable_if<std::is_floating_point<T>::value>::type>
    struct foo {
    
    };
    
    template <class T,
              class = typename std::enable_if<std::is_integral<T>::value>::type>
    bool is_even(T i) {return !bool(i%2);}
    
    int main()
    {
      // foo<int> f;  //error
      foo<float> f;   //ok
    
      //is_even(1.1); //error
      is_even(1); //ok
    
      return 0;
    }
    

    [edit]

    I must say above examples are not the best, and using static_assert would be recomended as it allows to generate informative error messages. SFINAE should not be used for parameter validation but rather for selecting another implementation depending on provided types.