Template and Virtual functions in C++ ? allowed ?
I've read over the web that template virtual functions are not allowed , is it true ? It's a little bit weird since this code compile great on my Eclipse's g++
template <class T>
class A {
public:
virtual ~A<T>() { }
virtual void printMe() {cout << "I am A class" << endl;}
};
template <class T>
cla开发者_Python百科ss B: public A<T> {
public:
void printMe() {cout << "I am B class" << endl;}
};
int main() {
A<int> * ptr = new B<int>;
ptr->printMe();
delete ptr;
return 0;
}
Regards,Ronen
virtual methods in a template type (as seen in your example) is valid.
the restriction you refer to takes this form:
class type {
//...
template <typename T> virtual void r() const;
};
What you have here is not a template virtual function, but rather a template class containing a ordinary virtual function.
As you have found, that is perfectly fine.
精彩评论