dimanche 10 juillet 2022

C++ CRTP override base class member function with minor change

I want to extend my base class by adding some possible postprocessing or preprocessing in some important util functions, and at the same time, I want to ensure that, calls to base class member function invokes the overriden functions of the most derived class.

These two ideas are what I'm considering of;

  1. Add preprocess() and postprocess() of derived class
  void func() {
    derived().func_pre();  
    // do the job of the base class
    derived().func_post();
  }

Truly awful, all derived class should implement func_pre() and func_post() even if they don't need.

  1. Call derived().func() from func()

Base class:

   void func() {
       derived().func()
   }

   void func_impl() {
       // do the job of the base class 
   }

Derived class:

   void func() {
       preprocess();
       base().func_impl();
       postprocess();
   }

Better than idea 1, but func() will be ill-formed if there is no CRTP derived class.

Better ideas?

Aucun commentaire:

Enregistrer un commentaire