I have a optional property event
that I define as a pointer in this struct:
struct AnimatedSprite {
//...some other properties
Event *event;
};
Let's say I want to store a StartTransitionEvent , defined like this:
class Event {
public:
Event() = default;
};
class StartTransitionEvent: public Event {
public:
int test = 1;
};
I can create and assign the StartTransitionEvent:
auto sprite = AnimatedSprite{};
auto newEvent = StartTransitionEvent{};
sprite.event = &newEvent;
But how do I get the type once I need to call something like:
eventBus->EmitEvent<StartTransitionEvent>(sprite->event);
Should I do some sort of checking on my event
pointer to get to the StartTransitionEvent? Or maybe not use pointers at all and go for a std::variant
to store the event with all it's possible child-classes?
CodePudding user response:
You could use double dispatch, a.k.a. visitor pattern and let the specific Event visit the EventBus.
So something like
class Event
{
public:
virtual void Emit(EventBus& eventBus) = 0;
};
class StartTransitionEvent : public Event
{
public:
void Emit(EventBus& eventBus) override
{
eventBus.EmitEvent(this);
}
};
sprite.event.Emit(eventBus);
CodePudding user response:
Assuming you're designing such a hierarchy, your EventBus
class should be able to work with the base Event
class. You achieve that through virtual functions in the Event
class:
struct Event {
Event() = default;
virtual ~Event() = default;
virtual void action1(); // event-specific actions
virtual void action2();
virtual void action3();
};
struct StartTransitionEvent : Event {
void action3() override; // override some actions
};
struct EventBus {
void emit(Event& event) {
// ...
event.action1();
// ...
event.action2();
// ...
event.action3();
}
};
int main() {
StartTransitionEvent event;
EventBus bus;
bus.emit(event);
}