VCCC  2024.05
VisualCamp Common C++ library
slot.h
Go to the documentation of this file.
1 # /*
2 # * Created by YongGyu Lee on 2021/06/03.
3 # */
4 #
5 # ifndef VCCC_SIGNAL_SLOT_H_
6 # define VCCC_SIGNAL_SLOT_H_
7 #
8 # include <functional>
9 # include <memory>
10 # include <utility>
11 # include <vector>
12 
13 namespace vccc {
14 
15 template<typename Func>
16 class slot;
17 
18 template<typename R, typename ...Args>
19 class slot<R(Args...)> {
20  public:
21  using return_type = R;
22  using function = std::function<R(Args...)>;
23  using weak_container = std::vector<std::weak_ptr<void>>;
24  using locked_container = std::vector<std::shared_ptr<void>>;
25 
26  slot(slot const&) = default;
27  slot(slot &&) = default;
28  slot& operator=(slot const&) = default;
29  slot& operator=(slot &&) = default;
30 
31  template<typename Func>
32  slot(const Func& func)
33  : func_(func) {}
34 
36  locked_container locked;
37  locked.reserve(tracked_objects_.size());
38 
39  for(const auto& w : tracked_objects_)
40  locked.emplace_back(w.lock());
41  return locked;
42  }
43 
44  bool expired() const {
45  for(const auto& w : tracked_objects_)
46  if (w.expired())
47  return true;
48  return false;
49  }
50 
51  template<typename ...U>
52  R operator()(U&&... args) const {
53  return func_(std::forward<U>(args)...);
54  }
55 
56  template<typename ...U>
57  R operator()(U&&... args) {
58  return func_(std::forward<U>(args)...);
59  }
60 
61  template<typename T>
62  slot& track(const std::shared_ptr<T> target) {
63  tracked_objects_.emplace_back(target);
64  return *this;
65  }
66 
67  slot& track(std::weak_ptr<void> target) {
68  tracked_objects_.emplace_back(target);
69  return *this;
70  }
71 
72  private:
73  function func_;
74  weak_container tracked_objects_;
75 };
76 
77 } // namespace vccc
78 
79 # endif // VCCC_SIGNAL_SLOT_H_
slot & track(std::weak_ptr< void > target)
Definition: slot.h:67
slot(slot &&)=default
R operator()(U &&... args) const
Definition: slot.h:52
std::vector< std::shared_ptr< void > > locked_container
Definition: slot.h:24
locked_container lock() const
Definition: slot.h:35
R operator()(U &&... args)
Definition: slot.h:57
slot & operator=(slot &&)=default
R return_type
Definition: slot.h:21
bool expired() const
Definition: slot.h:44
slot(const Func &func)
Definition: slot.h:32
std::vector< std::weak_ptr< void > > weak_container
Definition: slot.h:23
slot & track(const std::shared_ptr< T > target)
Definition: slot.h:62
slot(slot const &)=default
slot & operator=(slot const &)=default
Definition: slot.h:16
Definition: directory.h:12