I have heard that C++ class member function templates can't be virtual. Is this true?
If they can be virtual, what is an example of a scenario in which one would use such a function?
I have heard that C++ class member function templates can't be virtual. Is this true?
If they can be virtual, what is an example of a scenario in which one would use such a function?
The following code can be compiled and runs properly, using MinGW G++ 3.4.5 on Window 7:
and the output is:
And later I added a new class X:
When I tried to use class X in main() like this:
g++ report the following error:
So it is obvious that:
No, template member functions cannot be virtual.
At least with gcc 5.4 virtual functions could be template members but has to be templates themselves.
Outputs
Templates are all about the compiler generating code at compile-time. Virtual functions are all about the run-time system figuring out which function to call at run-time.
Once the run-time system figured out it would need to call a templatized virtual function, compilation is all done and the compiler cannot generate the appropriate instance anymore. Therefore you cannot have virtual member function templates.
However, there are a few powerful and interesting techniques stemming from combining polymorphism and templates, notably so-called type erasure.
In the other answers the proposed template function is a facade and doesn't offer any practical benefit.
The language doesn't allow virtual template functions but with a workaround it is possible to have both, e.g. one template implementation for each class and a virtual common interface.
It is however necessary to define for each template type combination a dummy virtual wrapper function:
Output:
Try it here