Content reproduced from the CSDN forum.
1, you can use virtual functions in a template class.
Exactly the same,
How to use virtual functions in non-template classes,
How to use it in the template class.
Template class<t>
Class A
{
Public
virtual void F1 () {cout<< "A is called" <<ENDL;} virtual function
virtual void F2 () =0{cout<< "a=0" <<ENDL;} Pure virtual function
};
Template class<t>
Class B:public A<t>
{
Public
void F1 () {cout<< "B is called" <<ENDL;}
void F2 () {cout<< "b!=0" <<ENDL;}
};
void Main ()
{
a<int>* p=new b<int>;
P->F1 (); Output B is called, virtual function succeeded
}
The only thing to note is:
A<int> and a<char> are two completely different classes.
The top code cannot be a<int>* p = new b<char>;
Because A<int> is not a base class for b<char>.
So we conclude that the template does not affect the polymorphism of the class.
2, a template member function may not be a virtual function.
Explanation 1:
The compiler expects to be able to determine the size of the virtual function table for this class when dealing with the definition of the class. If you allow a virtual member template function for a class, you must ask the compiler to know in advance all calls to that virtual member template function for that class in the program, which is not feasible.
Explanation 2:
When instantiating a template class, you need to create a vertual table.
It is not possible to determine how many function templates, including virtual function templates, join support, can be instantiated before the template class is instantiated.
The normal member function template doesn't matter what time you need to instantiate it, the compiler doesn't have to know how many to instantiate, the number of virtual functions must be known, otherwise the class cannot be instantiated (because you want to create virtual table). Therefore, virtual function templates are not currently supported.