dimanche 23 avril 2017

CRTP Pattern yet store inhomogenous types in a datastructure

I am interested in learning about CRTP. I would like to implement a component system for an engine and I dont want to access components unity style

GetComponent("withThisName");

but rather at compile time (unreal style)

GetComponent<FromThisType>();

While its rather easy to implement CRTP I dont really get how to manage CRTP derived classes in a datasructure without introducing dynamic dispatching again.

The Wiki describes an example with shapes:

// Base class has a pure virtual function for cloning
class Shape {
public:
    virtual ~Shape() {};
    virtual Shape *clone() const = 0;
};
// This CRTP class implements clone() for Derived
template <typename Derived>
class Shape_CRTP : public Shape {
public:
    virtual Shape *clone() const {
        return new Derived(static_cast<Derived const&>(*this));
    }
};

// Nice macro which ensures correct CRTP usage
#define Derive_Shape_CRTP(Type) class Type: public Shape_CRTP<Type>

// Every derived class inherits from Shape_CRTP instead of Shape
Derive_Shape_CRTP(Square) {};
Derive_Shape_CRTP(Circle) {};

In this example I would still be able to do something like

std::vector<Shape*> shapes;

BUT again there are virtual functions, and that is exactly what I tried to get rid of in the first place. I conclude, that I might still not get the CRTP right, or when it is used, on the other hand I see unreal engine using it, the way I want to use it.

Aucun commentaire:

Enregistrer un commentaire