GLIM
Loading...
Searching...
No Matches
callback_slot.hpp
1#pragma once
2
3#include <vector>
4#include <algorithm>
5#include <functional>
6
10template <typename Func>
12public:
13 CallbackSlot() {}
14 ~CallbackSlot() {}
15
21 int add(const std::function<Func>& callback) {
22 callbacks.push_back(callback);
23 return callbacks.size() - 1;
24 }
25
30 void remove(int callback_id) { callbacks[callback_id] = nullptr; }
31
37 operator bool() const {
38 return !callbacks.empty() && std::any_of(callbacks.begin(), callbacks.end(), [](const std::function<Func>& f) { return f; });
39 }
40
45 template <class... Args>
46 void call(Args&&... args) const {
47 if (callbacks.empty()) {
48 return;
49 }
50
51 for (const auto& callback : callbacks) {
52 if (callback) {
53 callback(args...);
54 }
55 }
56 }
57
62 template <class... Args>
63 void operator()(Args&&... args) const {
64 return call(args...);
65 }
66
67private:
68 std::vector<std::function<Func>> callbacks;
69};
Callback slot to hold and trigger multiple callbacks.
Definition callback_slot.hpp:11
void call(Args &&... args) const
Call all the registered callbacks.
Definition callback_slot.hpp:46
void operator()(Args &&... args) const
Call all the registered callbacks.
Definition callback_slot.hpp:63
int add(const std::function< Func > &callback)
Add a new callback.
Definition callback_slot.hpp:21
void remove(int callback_id)
Remove a callback.
Definition callback_slot.hpp:30