Suppose I have a template that works with raw pointers:
template<typename T> void processPointer(T* ptr);
I don't want this to be called with void*
pointers. It seems I have two choices. I can delete a non-template overload:
void processPointer(void*) = delete;
Or I can delete a template instantiation:
template<> void processPointer<void>(void*) = delete;
Declaring the non-template overload is easier (no futzing with angle brackets). Are there reasons why I'd prefer to delete the template instantiation instead?
In order for any code to appear, a template must be instantiated: the template arguments must be provided so that the compiler can generate an actual class (or function, from a function template).
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation to handle a specific set of template arguments is called a specialization.
Templates are very useful when implementing generic constructs like vectors, stacks, lists, queues which can be used with any arbitrary type. C++ templates provide a way to re-use source code as opposed to inheritance and composition which provide a way to re-use object code.
Implicit instantiation means that the compiler automatically generates the concrete function or class for the provided template arguments. In general, the compiler also deduces the template arguments from the function's arguments. In C++17, the compiler can also deduce the template arguments for class templates.
Here's one reason to favor the template version: processPointer<void>(void*)
can still be invoked directly, avoiding the other overload.
I don't see any reason to go templating here
In fact, by deleting the non-template overload you may wiggle your way out of some edge-case ambiguous calls that I can't think of right now, since non-templates take precedence over template instantiations. And thus make this work as desired in a majority of cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With