Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Templatized Virtual function

Tags:

c++

We know that C++ doesn't allow templated virtual function in a class. Anyone understands why such restriction?

like image 634
rayimag Avatar asked Aug 14 '09 12:08

rayimag


People also ask

Can you template a virtual function?

C++ expressly forbids virtual template functions because the virtual tables that would have to be built are way too complex. Luckily, C++ offers a way around this. It's a programming paradigm called Policy Based Design. In this article, I'll cover why you might need this, and how it works.

What is a template function?

Function templates are similar to class templates but define a family of functions. With function templates, you can specify a set of functions that are based on the same code but act on different types or classes. The following function template swaps two items: C++ Copy.

What is template in C++ with example?

A template is a simple yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types.

What is a template in OOP?

A template is a piece of code that can be copied and modified to fit a specific situation. Some templates show how, why, and when to use some feature of the language. Some templates show how to implement design patterns.


1 Answers

Short answer: Virtual functions are about not knowing who called whom until at run-time, when a function is picked from an already compiled set of candidate functions. Function templates, OTOH, are about creating an arbitrary number of different functions (using types which might not even have been known when the callee was written) at compile-time from the callers' sides. That just doesn't match.

Somewhat longer answer: Virtual functions are implemented using an additional indirection (the Programmer's General All-Purpose Cure), usually implemented as a table of function pointers (the so-called virtual function table, often abbreviated "vtable"). If you're calling a virtual function, the run-time system will pick the right function from the table. If there were virtual function templates, the run-time system would have to find the address of an already compiled template instance with the exact template parameters. Since the class' designer cannot provide an arbitrary number of function template instances created from an unlimited set of possible arguments, this cannot work.

like image 103
sbi Avatar answered Oct 21 '22 02:10

sbi