Template and Virtual functions in C++ ? allowed ?

为君一笑 提交于 2019-12-11 09:51:48

问题


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.



来源:https://stackoverflow.com/questions/7212818/template-and-virtual-functions-in-c-allowed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!