Home > OS >  How does typename assignment work in C (typename =)?
How does typename assignment work in C (typename =)?

Time:11-06

I came across this example when looking at std::enable_if:

template<class T,
typename = std::enable_if_t<std::is_array<T>::value> >
void destroy(T* t) 
{
   for(std::size_t i = 0; i < std::extent<T>::value;   i) {
    destroy((*t)[i]);
   }
}

In template argument lists, you can put untemplated classes/structs. So the above code is still possible when we remove the typename =. What does the typename = in this code mean and do?

CodePudding user response:

The typename on the 2nd template argument indicates the argument is a type rather than a constant value. The argument has no name specified, but the = indicates it has a default type if the caller doesn't specify one. In this case, that type is the result of enable_if_t<...> (aka std::enable_if<...>::type).

std::enable_if has 2 template arguments. The 1st argument takes in a boolean constant, and the 2nd argument specifies the type of the std::enable_if<...>::type member. The 2nd argument is void by default. The type member is defined only when the boolean is true, otherwise it is undefined when the boolean is false. In this case, that boolean is the result of std::is_array<T>::value.

So, if T is an array type, std::is_array<T>::value will be true, thus std::enable_if<true, void>::type will be void, and the final template will be:

template<class T, typename _ = void>
void destroy(T* t) 
{
   ...
}

Otherwise, if T is not an array type, std::is_array<T>::value will be false, thus std::enable_if<false, void>::type will be undefined, and the final template will be:

template<class T, typename _ = [undefined] >
void destroy(T* t) 
{
   ...
}

And thus the template will be disabled since it is invalid.

CodePudding user response:

First.
typename and class have the same meaning when used inside a template.

Second.
typename = ... means a default value has been specified for it which gets used if you do not explicitly specify a second parameter in the template.

  • Related