How to design around the limitation that templated member functions can't be virtual

别说谁变了你拦得住时间么 提交于 2019-11-28 12:18:33

Typically, double dispatch is used.

class Machine;
class Item {
public:
    virtual void bounce(Machine& mach);
};
class Machine {
public:
    template<typename T> void process(T& t);
    virtual void process(Item& i) {
        return i.bounce(*this);
    }
};
template<typename T> class CRTPItem {
public:
    virtual void bounce(Machine& mach) {
        return mach.process(*(T*)this);
    }
};
class ConcreteItem : public CRTPItem<ConcreteItem> {
public:
    // blah blah
};

In this case, you don't need virtual overhead for the whole ConcreteItem interface, and they don't need anything in common, just that one bounce function which is built for you automatically by inheriting from CRTPItem. This is only two vtable calls as opposed to the one you had originally, as opposed to needing a vtable call for all of Item's functions, and the interface can still retain all strong-typing that it would have if you could create virtual templates.

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