Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is deleting a template instantiation preferable to deleting a non-template overload?

Tags:

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?

like image 822
KnowItAllWannabe Avatar asked Jan 09 '14 18:01

KnowItAllWannabe


People also ask

Why we need to instantiate the template?

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).

What is instantiation of a 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.

When should you use a template C++?

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.

What is implicit instantiation?

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.


Video Answer


2 Answers

Here's one reason to favor the template version: processPointer<void>(void*) can still be invoked directly, avoiding the other overload.

like image 184
Casey Avatar answered Nov 07 '22 03:11

Casey


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.

like image 23
Lightness Races in Orbit Avatar answered Nov 07 '22 02:11

Lightness Races in Orbit