Веб-сайт самохостера Lotigara

summaryrefslogtreecommitdiff
path: root/source/application/discord/event.h
blob: 610887d1763dba7f9fc6d69da8c7e68e2852f2d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#pragma once

#include <functional>
#include <vector>

namespace discord {

template <typename... Args>
class Event final {
public:
    using Token = int;

    Event() { slots_.reserve(4); }

    Event(Event const&) = default;
    Event(Event&&) = default;
    ~Event() = default;

    Event& operator=(Event const&) = default;
    Event& operator=(Event&&) = default;

    template <typename EventHandler>
    Token Connect(EventHandler slot)
    {
        slots_.emplace_back(Slot{nextToken_, std::move(slot)});
        return nextToken_++;
    }

    void Disconnect(Token token)
    {
        for (auto& slot : slots_) {
            if (slot.token == token) {
                slot = slots_.back();
                slots_.pop_back();
                break;
            }
        }
    }

    void DisconnectAll() { slots_ = {}; }

    void operator()(Args... args)
    {
        for (auto const& slot : slots_) {
            slot.fn(std::forward<Args>(args)...);
        }
    }

private:
    struct Slot {
        Token token;
        std::function<void(Args...)> fn;
    };

    Token nextToken_{};
    std::vector<Slot> slots_{};
};

} // namespace discord