entt  2.4.1
delegate.hpp
1 #ifndef ENTT_SIGNAL_DELEGATE_HPP
2 #define ENTT_SIGNAL_DELEGATE_HPP
3 
4 
5 #include <utility>
6 
7 
8 namespace entt {
9 
10 
17 template<typename>
18 class Delegate;
19 
20 
34 template<typename Ret, typename... Args>
35 class Delegate<Ret(Args...)> final {
36  using proto_type = Ret(*)(void *, Args...);
37  using stub_type = std::pair<void *, proto_type>;
38 
39  static Ret fallback(void *, Args...) noexcept { return {}; }
40 
41  template<Ret(*Function)(Args...)>
42  static Ret proto(void *, Args... args) {
43  return (Function)(args...);
44  }
45 
46  template<typename Class, Ret(Class::*Member)(Args...)>
47  static Ret proto(void *instance, Args... args) {
48  return (static_cast<Class *>(instance)->*Member)(args...);
49  }
50 
51 public:
53  Delegate() noexcept
54  : stub{std::make_pair(nullptr, &fallback)}
55  {}
56 
61  template<Ret(*Function)(Args...)>
62  void connect() noexcept {
63  stub = std::make_pair(nullptr, &proto<Function>);
64  }
65 
77  template<typename Class, Ret(Class::*Member)(Args...)>
78  void connect(Class *instance) noexcept {
79  stub = std::make_pair(instance, &proto<Class, Member>);
80  }
81 
87  void reset() noexcept {
88  stub = std::make_pair(nullptr, &fallback);
89  }
90 
96  Ret operator()(Args... args) {
97  return stub.second(stub.first, args...);
98  }
99 
108  bool operator==(const Delegate<Ret(Args...)> &other) const noexcept {
109  return stub.first == other.stub.first && stub.second == other.stub.second;
110  }
111 
112 private:
113  stub_type stub;
114 };
115 
116 
128 template<typename Ret, typename... Args>
129 bool operator!=(const Delegate<Ret(Args...)> &lhs, const Delegate<Ret(Args...)> &rhs) noexcept {
130  return !(lhs == rhs);
131 }
132 
133 
134 }
135 
136 
137 #endif // ENTT_SIGNAL_DELEGATE_HPP
EnTT default namespace.
Definition: family.hpp:9
Delegate() noexcept
Default constructor.
Definition: delegate.hpp:53
Basic delegate implementation.
Definition: delegate.hpp:18
bool operator==(const Delegate< Ret(Args...)> &other) const noexcept
Checks if the contents of the two delegates are different.
Definition: delegate.hpp:108
void connect(Class *instance) noexcept
Connects a member function for a given instance to a delegate.
Definition: delegate.hpp:78
void connect() noexcept
Binds a free function to a delegate.
Definition: delegate.hpp:62
Ret operator()(Args... args)
Triggers a delegate.
Definition: delegate.hpp:96
void reset() noexcept
Resets a delegate.
Definition: delegate.hpp:87
constexpr bool operator!=(const HashedString &lhs, const HashedString &rhs) noexcept
Compares two hashed strings.