Can I get polymorphic behavior without using virtual functions?

后端 未结 11 1367
栀梦
栀梦 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:36

    I think it is possible with CRTP (if your 'Device' supports Templates).

    #include 
    
    template struct base{
        void g(){
            if(T *p = static_cast(this)){
                p->f();
            }
        }
        void f(){volatile int v = 0; std::cout << 1;}
        virtual ~base(){}
    };
    
    struct derived1 : base{
        void f(){std::cout << 2;}
    };
    
    struct derived2 : base{
        void f(){std::cout << 3;}
    };
    
    int main(){
        derived1 d1;
        d1.g();
    
        derived2 d2;
        d2.g();
    }
    

提交回复
热议问题