vendredi 18 septembre 2020

How to initialize a generic base class in c++

I am trying to rewrite some old code to make it more Object oriented. previously I have a union of struct called, say Event

union Event {
  AEvent aEvent;
  BEvent bEvent;
  CEvent cEvent;
}

and this Event is later used in a struct

struct EventImpl {
  ... //some other members 
  Event event();
}

now I am trying to use the powerful shared_ptr; I created a new base class called BaseEvent

class BaseEvent{
    size_t m_TypeHash; 
    public: 
        using Ptr = std::shared_ptr<BaseEvent>;
        virtual ~EventDesc() = default; 
        
        template <class T>
        // cast to different events
        static std::shared_ptr<T> Cast(const Ptr& src) {
            return src->m_TypeHash == typeid(T).hash_code() 
                ? std::static_pointer_cast<T>(src)
                : nullptr;
        }
    protected: 
        BaseEvent(size_t typeHash) : m_TypeHash(typeHash){}
};

From here, AEvent, BEvent and CEvent can just extend BaseEvent, which makes the code cleaner.

But the question arises, what do I with the struct EventImpl that contains Event?? Is there a way to initialize a generic BaseEvent?

struct EventImpl {
  ... //some other members 
  BaseEvent<T> event; //??
  T event; // ??
  std::shared_ptr<BaseEvent> event; // ???
}

Aucun commentaire:

Enregistrer un commentaire