Molybden
Loading...
Searching...
No Matches
delegate.hpp
1// Copyright (c) 2000-2023 TeamDev Ltd. All rights reserved.
2// TeamDev PROPRIETARY and CONFIDENTIAL.
3// Use is subject to license terms.
4
5#ifndef MOLYBDEN_DELEGATE_HPP
6#define MOLYBDEN_DELEGATE_HPP
7
8#include <functional>
9#include <memory>
10#include <mutex>
11
12namespace molybden {
13
29template <typename Args, typename Action>
30class Delegate {
31 public:
35 using Signature = void(const Args& args, Action action);
36
53 Delegate& operator=(std::function<Signature> callback);
54
58 void reset();
59
60 private:
61 std::mutex callback_mutex_;
62 std::function<Signature> callback_;
63
64 void operator()(const Args& args, Action action);
65
66 friend class ObservableOwner;
67};
68
69template <typename Args, typename Action>
71 std::function<Signature> callback) {
72 std::lock_guard<std::mutex> guard(callback_mutex_);
73 callback_ = callback;
74 return *this;
75}
76
77template <typename Args, typename Action>
78void Delegate<Args, Action>::operator()(const Args& args, Action action) {
79 std::lock_guard<std::mutex> guard(callback_mutex_);
80 if (callback_) {
81 callback_(args, std::move(action));
82 }
83}
84
85template <typename Args, typename Action>
87 std::lock_guard<std::mutex> guard(callback_mutex_);
88 callback_ = nullptr;
89}
90
91} // namespace molybden
92
93#endif // MOLYBDEN_DELEGATE_HPP
The base API that implements classes which represent delegate's action.
Definition delegate_action.hpp:18
Delegates allow you to make decisions that affect the application behavior.
Definition delegate.hpp:30
void reset()
Resets the callback registered for this delegate.
Definition delegate.hpp:86
Delegate & operator=(std::function< Signature > callback)
Registers a callback to be invoked by this delegate.
Definition delegate.hpp:70
void(const Args &args, Action action) Signature
The callback's signature.
Definition delegate.hpp:35