Is it safe if a template contains virtual function?

冷暖自知 提交于 2019-12-10 17:33:11

问题


Early binding for template and late binding for virtual function. Therefore, is it safe if a template contains virtual function?

template<typename T> 
class base {
public:
    T data;
    virtual void fn(T t){}
};

回答1:


It is completely safe. Once you instantiate the class template, it becomes normal class just like other classes.

template<typename T> 
class base {
public:
    T data;
    virtual void fn(T t){}
};


class derived : base<int> {
public:
    virtual void fn(int t){} //override
};

base<int> *pBase = new derived();
pBase->fn(10); //calls derived::fn()

I would also like to point out that while it is allowed virtual function in a class template, it is not allowed virtual function template inside a class (as shown below):

class A
{
   template<typename T>
   virtual void f(); //error: virtual function template is not allowed
};



回答2:


Yes, it's quite safe. You'd use it by having a class derive from it:

class derived : public base<int> {
    virtual void fn(int) { std::cout << "derived"; }
};

Of course, if it contains any other virtual functions (i.e., is intended to be used as a base class) you generally want to make the dtor virtual as well.




回答3:


There is no safety concern associated with virtual function inside a template class. It is as good as, having a virtual function inside a normal class.



来源:https://stackoverflow.com/questions/7962570/is-it-safe-if-a-template-contains-virtual-function

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