0

I am reading reference about enable_if on cppreference. In the example section. I have a question about the template declaration in the code:

// #4, enabled via a template parameter
template<class T,
         typename std::enable_if<
             !std::is_trivially_destructible<T>{} &&
             (std::is_class<T>{} || std::is_union<T>{}),
            int>::type = 0>
void destroy(T* t)
{
    std::cout << "destroying non-trivially destructible T\n";
    t->~T();
}

If the condition of the std::enable_if() is satisfied. The declaration can be rewrote as:

 template<class T, typename std::enable_if_t<true,int> = 0> // #1

Since the possible implementation of enable_if is:

template<class T>
struct enable_if<true, T> { typedef T type; };

The #1 is equivalent to the following statement:

template<typename T, typename int = 0>

which is an ill-formed statement. The compiler spits an error message:

error: two or more data types in declaration of 'parameter'
 template<typename T, typename int = 0>

My question is: What is the correctly way to understand the typename std::enable_if_t<true,int> = 0 in the template declaration.


And a similar question I have is the example followed by #4
The #5 :

// #5, enabled via a template parameter
template<class T,
    typename = std::enable_if_t<std::is_array<T>::value> >
void destroy(T* t) // note, function signature is unmodified
{
    for(std::size_t i = 0; i < std::extent<T>::value; ++i) {
        destroy((*t)[i]);
    }
}

When the condition of the enable_if() is satisfied, the declaration should be something like:

template<class T, typename = X > // X is a type name

How comes the typename=X can be compiled.

Thanks,

Rong

r0n9
  • 2,505
  • 1
  • 29
  • 43
  • 5
    You are slightly mistaken. `template::type = 0>` is equivalent to `template`. You don't need to `typename` to resolve the dependent type when you use `std::enable_of_t`, – NathanOliver Nov 16 '17 at 00:21
  • Or you can use `typename` with a variadic version: `typename std::enable_if::type ...` – cantordust Nov 16 '17 at 00:31
  • https://stackoverflow.com/questions/34459640/what-does-typename-enable-void-mean – r0n9 Nov 16 '17 at 02:59

0 Answers0