Search code examples
c++oopincludeheader-filesevent-listener

C++ Include Problem in Event Listener Pattern


I am trying to use EventListener Pattern (instead of Observer) in my project. Basically:

  1. Entitys can register themselves as listeners for certain types of Events
  2. Entitys can report an Event to EventListener.
  3. When an Event is being reported, EventListener will notify Entity instances that are registered to receive this type of Event.

The two classes are:

class Entity:
void Register(std::string type); // calls EventListener::RegisterListener(this, type);
void ReportEvent(Event event); // calls EventListener::BroadcastEvent(event);
void OnNotify(Event event); // called by EventListener::BroadcastEvent(event);

class EventListener:
void RegisterListener(Entity* listener, Event event);
void BroadcastEvent(Event event); // calls Entity::OnNotify(event) for all relative Entity instances

Notice that in Entity::ReportEvent() calls EventListener::RegisterListener(), and EventListener::BroadcaseEvent() calls Entity::OnNotify(). Doing a simple forward declaration cannot enable this dual-linked calling. What should I do? Can I directly #include each other in their .hpp files (Which I highly doubt)?


Solution

  • The solution is way easier than I thought. You can directly #include the header files with each other. Just remember to add the header guards (#ifndef ENTITY_HPP #define ENTITY_HPP #endif).