Search code examples
c++templatesenable-if

Whats is type* in the expression std::enable_if


Could someone please explain to me what type* means ?

I see in the documentation on std::enable_if this example:

// #3, enabled via a parameter
template<class T>
void destroy(
      T* t, 
      typename std::enable_if<std::is_trivially_destructible<T>::value>::type* = 0
    ){
    std::cout << "destroying trivially destructible T\n";
 }

Why do we use type here and what is type* ?

Thanks!


Solution

  • It's a pointer to a type exposed by std::enable_if if std::is_trivially_destructible<T>::value == true else it doesn't exist. The default type for it to expose is void.

    Remember, with SFINAE we're only trying to trigger a substitution error, we can do this by trying to use the typedef type of std::enable_if. If std::is_trivially_destructible<T>::value is false then type won't exist and the function will be skipped for overload resolution.

    We could also specify our own type, maybe that makes it clear:

    std::enable_if<true, int>::type* intPointer;
    

    Here, intPointer will be of type int*.


    Without the checks of enable_if it'd look a bit like:

    template <typename T>
    struct enable_always
    {
      typedef T type;
    };