LearnFrenzy
Sign in Take a free test

Templates · Template Programs · Question 4

Type-safe event bus with templates in C++ Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

Write an EventBus with template functions subscribe<E>(handler) and publish(const E&), so each event type has its own list of handlers and handlers receive the correct type.

Solution
main.cpp
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <typeindex>
#include <vector>

class EventBus {
    struct Base { virtual ~Base() = default; };
    template <typename E>
    struct Handlers : Base { std::vector<std::function<void(const E&)>> list; };
    std::map<std::type_index, std::unique_ptr<Base>> by_type_;

    template <typename E>
    Handlers<E>& handlers() {
        auto& slot = by_type_[std::type_index(typeid(E))];
        if (!slot) slot = std::make_unique<Handlers<E>>();
        return static_cast<Handlers<E>&>(*slot);
    }
public:
    template <typename E>
    void subscribe(std::function<void(const E&)> f) { handlers<E>().list.push_back(std::move(f)); }
    template <typename E>
    int publish(const E& e) {
        auto& h = handlers<E>();
        for (auto& f : h.list) f(e);
        return static_cast<int>(h.list.size());
    }
};

struct UserJoined { std::string name; };
struct OrderPlaced { int id; double amount; };

int main() {
    EventBus bus;
    bus.subscribe<UserJoined>([](const UserJoined& e) { std::cout << "welcome mail to " << e.name << '\n'; });
    bus.subscribe<UserJoined>([](const UserJoined& e) { std::cout << "analytics: +1 user (" << e.name << ")\n"; });
    bus.subscribe<OrderPlaced>([](const OrderPlaced& e) { std::cout << "invoice #" << e.id << " for " << e.amount << '\n'; });
    int a = bus.publish(UserJoined{"Asha"});
    int b = bus.publish(OrderPlaced{1042, 1499.5});
    int c = bus.publish(42);                 // nobody listens for int
    std::cout << a << b << c << '\n';
    return 0;
}

Output Verified by compiling and running

welcome mail to Asha
analytics: +1 user (Asha)
invoice #1042 for 1499.5
210

Templates create a separate handler list type per event; std::type_index maps each event type to its list. Subscribers always get the exact event type – no casting in user code.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links