entt  2.6.1
delegate.hpp
1 #ifndef ENTT_SIGNAL_DELEGATE_HPP
2 #define ENTT_SIGNAL_DELEGATE_HPP
3 
4 
5 #include <utility>
6 #include "../config/config.h"
7 
8 
9 namespace entt {
10 
11 
18 template<typename>
19 class Delegate;
20 
21 
35 template<typename Ret, typename... Args>
36 class Delegate<Ret(Args...)> final {
37  using proto_fn_type = Ret(void *, Args...);
38  using stub_type = std::pair<void *, proto_fn_type *>;
39 
40  template<Ret(*Function)(Args...)>
41  static Ret proto(void *, Args... args) {
42  return (Function)(args...);
43  }
44 
45  template<typename Class, Ret(Class:: *Member)(Args...)>
46  static Ret proto(void *instance, Args... args) {
47  return (static_cast<Class *>(instance)->*Member)(args...);
48  }
49 
50 public:
52  Delegate() ENTT_NOEXCEPT
53  : stub{}
54  {}
55 
60  bool empty() const ENTT_NOEXCEPT {
61  // no need to test also stub.first
62  return !stub.second;
63  }
64 
69  template<Ret(*Function)(Args...)>
70  void connect() ENTT_NOEXCEPT {
71  stub = std::make_pair(nullptr, &proto<Function>);
72  }
73 
85  template<typename Class, Ret(Class:: *Member)(Args...)>
86  void connect(Class *instance) ENTT_NOEXCEPT {
87  stub = std::make_pair(instance, &proto<Class, Member>);
88  }
89 
95  void reset() ENTT_NOEXCEPT {
96  stub.second = nullptr;
97  }
98 
104  Ret operator()(Args... args) const {
105  return stub.second(stub.first, args...);
106  }
107 
116  bool operator==(const Delegate<Ret(Args...)> &other) const ENTT_NOEXCEPT {
117  return stub.first == other.stub.first && stub.second == other.stub.second;
118  }
119 
120 private:
121  stub_type stub;
122 };
123 
124 
136 template<typename Ret, typename... Args>
137 bool operator!=(const Delegate<Ret(Args...)> &lhs, const Delegate<Ret(Args...)> &rhs) ENTT_NOEXCEPT {
138  return !(lhs == rhs);
139 }
140 
141 
142 }
143 
144 
145 #endif // ENTT_SIGNAL_DELEGATE_HPP
constexpr bool operator!=(const HashedString &lhs, const HashedString &rhs) ENTT_NOEXCEPT
Compares two hashed strings.
void connect() ENTT_NOEXCEPT
Binds a free function to a delegate.
Definition: delegate.hpp:70
Ret operator()(Args... args) const
Triggers a delegate.
Definition: delegate.hpp:104
EnTT default namespace.
Definition: algorithm.hpp:10
Basic delegate implementation.
Definition: delegate.hpp:19
Delegate() ENTT_NOEXCEPT
Default constructor.
Definition: delegate.hpp:52
bool operator==(const Delegate< Ret(Args...)> &other) const ENTT_NOEXCEPT
Checks if the contents of the two delegates are different.
Definition: delegate.hpp:116
bool empty() const ENTT_NOEXCEPT
Checks whether a delegate actually stores a listener.
Definition: delegate.hpp:60
void reset() ENTT_NOEXCEPT
Resets a delegate.
Definition: delegate.hpp:95
void connect(Class *instance) ENTT_NOEXCEPT
Connects a member function for a given instance to a delegate.
Definition: delegate.hpp:86