vendredi 11 juin 2021

How to avoid static_cast in Pub/Sub system? (C++)

I'm designing a simple Pub/Sub system (based on Boost Signals2). In this system, you can subscribe, via EventManager::subscribe, to specific types of events. It's frustrating, however, for each subscriber to have to cast const Event& to the specific event which they have subscribed to. What's a good/ elegant way to avoid this problem? I'm happy to switch to a very different design.

#include <iostream>
#include <functional>
#include <string>

class Event {
  virtual std::string get_type() = 0;
};

class EventA : public Event {
  std::string get_type() override {
    return "EVENT_A";
  }
  int get_foo() {
    return 5;
  }
};

class EventManager {
 public:
  void publish_event(const Event &e);
  void subscribe(std::string type, std::function<void(const Event &)> subscriber);
};

int main() {
  EventManager event_manager;
  event_manager.subscribe("EVENT_A", [&](const Event &e) {
    const EventA &event_a = static_cast<const EventA &>(e); // how can avoid cast here?
    // do stuff with event_a
  });

  EventA event_a;
  event_manager.publish_event(event_a);
}

Aucun commentaire:

Enregistrer un commentaire