mercredi 1 avril 2020

How can I avoid virtual call overhead when using crtp with common interface class?

I am using CRTP for performance reasons, so I have this hierarchy :

template <typename Derived>
class Base{
  public:
    double do_sthing(){
      static_cast<Derived*>(this)->do_sthing();
      }
};

class DerivedA : public Base<DerivedA>{
  public:
    inline double do_sthing(){ ... }
 };

class DerivedB : public Base<DerivedB>{
  public:
    inline double do_sthing(){ ... }
  };

But now I want to put objects of type DerivedA and DerivedB in a vector and do the following kind of code :

 for(auto obj : my_vector) {
   obj->do_sthing();
 }

my solution was to create a common interface class from which Base will inherit :

class Interface {
  virtual void do_sthing() = 0;
};

But in this case I am incurring the virtual call overhead, and I did all the CRTP to avoid it. Is there a manner to avoid that? I thought of declaring the method do_sthing in Base as final.

Aucun commentaire:

Enregistrer un commentaire