add subscription reference "counting" RAII wrapper
This commit is contained in:
parent
9a4df12d68
commit
a42ce1a9e0
@ -8,6 +8,37 @@ template<typename EventI>
|
|||||||
struct EventProviderI {
|
struct EventProviderI {
|
||||||
using enumType = typename EventI::enumType;
|
using enumType = typename EventI::enumType;
|
||||||
|
|
||||||
|
// keeps track of subscriptions for you
|
||||||
|
// and destorys them on destruction
|
||||||
|
struct SubscriptionReference {
|
||||||
|
EventProviderI& _ep;
|
||||||
|
EventI* _object {nullptr};
|
||||||
|
std::vector<enumType> _subs;
|
||||||
|
|
||||||
|
SubscriptionReference(EventProviderI& ep, EventI* object) :
|
||||||
|
_ep(ep), _object(object)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
~SubscriptionReference(void) {
|
||||||
|
for (const enumType et : _subs) {
|
||||||
|
auto& o_vec = _ep._subscribers.at(static_cast<size_t>(et));
|
||||||
|
for (auto o_it = o_vec.cbegin(); o_it != o_vec.cend(); o_it++) {
|
||||||
|
if (*o_it == _object) {
|
||||||
|
o_vec.erase(o_it);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
SubscriptionReference& subscribe(const enumType event_type) {
|
||||||
|
_ep._subscribers.at(static_cast<size_t>(event_type)).push_back(_object);
|
||||||
|
_subs.push_back(event_type);
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
virtual ~EventProviderI(void) {};
|
virtual ~EventProviderI(void) {};
|
||||||
|
|
||||||
// TODO: unsub
|
// TODO: unsub
|
||||||
@ -15,6 +46,10 @@ struct EventProviderI {
|
|||||||
_subscribers.at(static_cast<size_t>(event_type)).push_back(object);
|
_subscribers.at(static_cast<size_t>(event_type)).push_back(object);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
SubscriptionReference newSubRef(EventI* object) {
|
||||||
|
return SubscriptionReference{*this, object};
|
||||||
|
}
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
template<typename T>
|
template<typename T>
|
||||||
bool dispatch(enumType event_type, const T& event) {
|
bool dispatch(enumType event_type, const T& event) {
|
||||||
|
Loading…
Reference in New Issue
Block a user