Can I get polymorphic behavior without using virtual functions?

后端 未结 11 1358
栀梦
栀梦 2020-12-03 13:54

Because of my device I can\'t use virtual functions. Suppose I have:

class Base
{
    void doSomething() { }
};

class Derived : public Base
{
    void doSom         


        
11条回答
  •  無奈伤痛
    2020-12-03 14:42

    You can make your own vtable, I suppose. I'd just be a struct containing your "virtual" function pointers as part of Base, and have code to set up the vtable.

    This is kind of a gross solution -- it's the C++ compiler's job to handle this feature.

    But here goes:

    #include 
    
    class Base
    {
    protected:
        struct vt {
            void (*vDoSomething)(void);
        } vt;
    private:
        void doSomethingImpl(void) { std::cout << "Base doSomething" << std::endl; }
    public:
        void doSomething(void) { (vt.vDoSomething)();}
        Base() : vt() { vt.vDoSomething = (void(*)(void)) &Base::doSomethingImpl;}
    };
    
    class Derived : public Base
    {
    public:
        void doSomething(void) { std::cout << "Derived doSomething" << std::endl; }
        Derived() : Base() { vt.vDoSomething = (void(*)(void)) &Derived::doSomething;}
    };
    

提交回复
热议问题