#include <iostream>
#include <vector>
#include <memory>
#include <functional>
class EventManager
{
public:
template<class F>
void AddClient(const F& receiver)
{
clients.emplace_back(new EventClient<F>(receiver));
}
void Emit()
{
for (const auto& client : clients)
{
client->Respond();
}
}
private:
struct IEventClient {
virtual ~IEventClient(){}
virtual void Respond() = 0;
};
template<class F>
struct EventClient : IEventClient
{
const F& f;
EventClient(const F& f) : f(f){}
void Respond() override { f(); }
};
std::vector<std::unique_ptr<IEventClient>> clients;
};
struct Foo
{
void operator()() const { std::cout << "I'm a Foo!\n"; }
};
int main() {
EventManager eventMan;
eventMan.AddClient([]{ std::cout << "yo\n"; });
std::function<void()> f = []{ std::cout << "I'm a std function!\n"; };
eventMan.AddClient(f);
eventMan.AddClient(Foo());
eventMan.Emit();
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgojaW5jbHVkZSA8bWVtb3J5PgojaW5jbHVkZSA8ZnVuY3Rpb25hbD4KCmNsYXNzIEV2ZW50TWFuYWdlcgp7CnB1YmxpYzoKCXRlbXBsYXRlPGNsYXNzIEY+Cgl2b2lkIEFkZENsaWVudChjb25zdCBGJiByZWNlaXZlcikKCXsKCQljbGllbnRzLmVtcGxhY2VfYmFjayhuZXcgRXZlbnRDbGllbnQ8Rj4ocmVjZWl2ZXIpKTsKCX0KCQoJdm9pZCBFbWl0KCkKCXsKCQlmb3IgKGNvbnN0IGF1dG8mIGNsaWVudCA6IGNsaWVudHMpCgkJewoJCQljbGllbnQtPlJlc3BvbmQoKTsKCQl9Cgl9CgkKcHJpdmF0ZToKCXN0cnVjdCBJRXZlbnRDbGllbnQgewoJCXZpcnR1YWwgfklFdmVudENsaWVudCgpe30KCQl2aXJ0dWFsIHZvaWQgUmVzcG9uZCgpID0gMDsKCX07CgkKCXRlbXBsYXRlPGNsYXNzIEY+CglzdHJ1Y3QgRXZlbnRDbGllbnQgOiBJRXZlbnRDbGllbnQKCXsKCQljb25zdCBGJiBmOwoJCUV2ZW50Q2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