Template and Virtual functions in C++ ? allowed ?

2019-08-03 06:41发布

问题:

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>
class 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

回答1:

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;
};


回答2:

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.