62 lines
1.7 KiB
C++
62 lines
1.7 KiB
C++
/// @file Event.hpp
|
|
/// @description Templated Event Hook Class modeled after C# events
|
|
/// @author Josh O'Leary - Redacted Software
|
|
/// @revision 3
|
|
/// @lastedit 2024-02-21
|
|
/// @license Unlicense - Public Domain
|
|
|
|
#pragma once
|
|
|
|
#include <chrono>
|
|
#include <functional>
|
|
|
|
// TODO: Document & Explain this
|
|
|
|
#include <EventConnection.h>
|
|
|
|
template <typename ... Args>
|
|
class EventConnection;
|
|
|
|
template <typename ... Args>
|
|
class Event {
|
|
public:
|
|
using delegate = std::function<void(Args...)>;
|
|
using connection = EventConnection<Args ...>;
|
|
using event_ptr = std::shared_ptr<connection>;
|
|
public:
|
|
void Await(Args& ... arg);
|
|
void Invoke(Args... args);
|
|
void operator()(Args... args);
|
|
connection Connect(delegate callback);
|
|
void Disconnect(connection &conn);
|
|
connection operator+=(delegate callback);
|
|
private:
|
|
std::vector<event_ptr> listeners;
|
|
uint64_t listenerCounter = 0;
|
|
};
|
|
|
|
template<typename... Args>
|
|
EventConnection<Args...> Event<Args...>::operator+=(Event::delegate callback) { return Connect(callback); }
|
|
|
|
template<typename... Args>
|
|
void Event<Args...>::operator()(Args... args) { Invoke(args...);}
|
|
|
|
template <typename ... Args>
|
|
void Event<Args...>::Invoke(Args... args) {
|
|
for (event_ptr &connection_ptr: this->listeners) {
|
|
connection_ptr->Invoke(args...);
|
|
}
|
|
}
|
|
|
|
template <typename ... Args>
|
|
EventConnection<Args...> Event<Args...>::Connect(delegate callback)
|
|
{
|
|
event_ptr retval(new connection(this, callback));
|
|
this->listeners.push_back(retval);
|
|
return *retval;
|
|
}
|
|
|
|
template <typename ... Args>
|
|
void Event<Args...>::Disconnect(connection &conn) {
|
|
listeners.erase(std::remove(listeners.begin(), listeners.end(), 99), listeners.end());
|
|
} |