-2

Here is a code I have got from here:

class Deletor {
    public:  virtual ~Deletor() {}
};

template<typename T> class Base : public Deletor {
    public: 

        int  Run() { return static_cast<T*>(this)->DoIt(); }
};

class Derived1 : public Base<Derived1> {
    ...
    public:
        int  DoIt() { /* the actual implementation for Derived1 */  }
};

class Derived2 : public Base<Derived2> {
    ...
    public:
        int  DoIt() { /* the actual implementation for Derived2 */  }
};

int main() {
    Derived1 Obj1;
    Derived2 Obj2;

    Obj1.Run(); /* runs the actual DoIt() implementation */
    Obj2.Run(); /* runs the actual DoIt() implementation */
};

I look and this code and think why I ned to use inheritance or CRTP to achieve this? I could just write two unrelated classes that both implement Run() method. What I miss here?

1

It gets interesting when Run does other things besides just calling DoIt, and DoIt is just a customization point. So basically,Run is a complicated operation, with small variations. Those variations are achieved by various DoIt functions in the different subclasses, while the bulk of the code is shared.

For example, the base class could be a helper to implement smart pointers. That requires quite a bit of boilerplate code (the *, ->, !, ==, !=, and bool conversion operators), which all really come down to the single question of "give me a raw pointer", usually called get(). It's possible to share all this boilerplate in a CRTP base and only implement get() in the derived classes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.