Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

templating virtual functions not possible. Only a temporary technical limitation?

Tags:

c++

templates

I understand that you can't declare a virtual method as templated, because the compiler would not know how much entries to reserve in the virtual table. This is, however, a technical limitation, rather than a language one. The compiler could know how many instances of the template are actually needed, and "go back" to allocate a proper vtable size.

Is there a planned technical solution in the upcoming standard?

like image 825
Stefano Borini Avatar asked Mar 27 '13 12:03

Stefano Borini


People also ask

Can templates have virtual functions?

No, template member functions cannot be virtual.

Can you overload template functions?

You may overload a function template either by a non-template function or by another function template. The function call f(1, 2) could match the argument types of both the template function and the non-template function.

What is true about function templates?

Explanation: As a template feature allows you to write generic programs. therefore a template function works with any type of data whereas normal function works with the specific types mentioned while writing a program. Both normal and template function accepts any number of parameters.

Can a class member function template be virtual?

Member template functions cannot be virtual functions and cannot override virtual functions from a base class when they are declared with the same name as a base class virtual function.


1 Answers

The compiler can never know all of the possible instantiations of a template. Under the current compilation model, each translation unit is compiled separately and later linked. When compiling a template type in one translation unit, you do not know the instantiations of that type in another.

Imagine you're writing a library and you want a template function in it. You compile the library and then distribute it to your clients. Now the clients can instantiate your template function with whatever template arguments they like, but your library has already been compiled! It can't "go back" and change this.

You're assuming that when you compile the template function, you also have available every instantiation of that function. That's often not the case and, under the current compilation and linking model, cannot be known to be the case.

like image 128
Joseph Mansfield Avatar answered Oct 13 '22 19:10

Joseph Mansfield