Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member function templates cannot be declared virtual - From Addison Wesley: C++ Templates

From Addison Wesley: C++ Templates

Member function templates cannot be declared virtual. This constraint is imposed because the usual implementation of the virtual function call mechanism uses a fixed-size table with one entry per virtual function. However, the number of instantiations of a member function template is not fixed until the entire program has been translated.

Does the above quote mean that templates have static binding and virtual functions have dynamic binding, that's the reason there cannot be virtual function templates? Please see if a explanation in layman's language is possible.

like image 939
Aquarius_Girl Avatar asked Apr 21 '11 10:04

Aquarius_Girl


People also ask

Can a member function template be virtual?

No, template member functions cannot be virtual.

What functions Cannot be virtual?

A virtual function cannot be global or static because, by definition, a virtual function is a member function of a base class and relies on a specific object to determine which implementation of the function is called. You can declare a virtual function to be a friend of another class.

How do you define a virtual function in C++?

A virtual function is a member function in the base class that we expect to redefine in derived classes. Basically, a virtual function is used in the base class in order to ensure that the function is overridden. This especially applies to cases where a pointer of base class points to an object of a derived class.

How do you call a function template in C++?

Defining a Function TemplateA function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.


1 Answers

Yes, and no.

The most popular method to resolve virtual function calls is to use a table ("vtable"), where each virtual function maps to an index in the table. This more or less requires that you know the size of the table.

With templates, new functions will be created as needed in different modules. You would then either have to convince the linker to build the table after figuring out the final number of functions, or use some kind of runtime structure to search for available functions at runtime.

On many systems, the linker is part of the OS and knows nothing about C++, so that option is limited. A runtime search would of course affect the performance negatively, perhaps for all virtual functions.

So, in the end, it was decided that it just was not worth the trouble of introducing virtual templates into the language.

like image 54
Bo Persson Avatar answered Sep 18 '22 23:09

Bo Persson