开发者

Template and Virtual functions in C++ ? allowed ?

开发者 https://www.devze.com 2023-03-31 17:11 出处:网络
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++

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消