typename as a type template parameter

What does "typename = ..." mean in the code below? Is it a type template parameter? but it evaluates to void if T is an array??


1
2
3
4
5
6
7
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]);
    }
}
Is it a type template parameter?

Yes.

It is an unnamed type template parameter.

What's to the right of the = is the default value that will be used if you do not specify.

Although, when enable_if is used like this it is not the intention that the template argument should ever be explicitly specified by the caller or that it should be used inside the function body. It's just a "hack" to disable template instantiation for certain types.

If you pass a pointer to a type that is not an array type it will not instantiate the template. If there is no other matching template specialization that matches the arguments it will lead to a compilation error.

1
2
3
4
5
6
7
8
9
10
11
template<class T, typename = std::enable_if_t<std::is_array_v<T>>>
void destroy(T* t) { }

int main()
{
	int arr1[] = {1, 2, 3};
	destroy(&arr1); // OK
	
	int* arr2 = new int[3];
	destroy(&arr2); // Error
}

You might want to look up SFINAE if you're interested in this technique, but since C++20 we normally use requires instead because it's both easier to use and more efficient to compile.

1
2
3
template<class T>
requires (std::is_array_v<T>)
void destroy(T* t) { }
Last edited on
Just a small further point. You can use typename instead of class in the template <>.

1
2
template<typename T, typename = std::enable_if_t<std::is_array_v<T>>>
...

Topic archived. No new replies allowed.