Treehopper C++ API
Event.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <functional>
4 #include <vector>
5 #include <algorithm>
6 #include <iostream>
7 
8 namespace Treehopper {
9  using namespace std;
10 
67  template<class Sender, class EventArgs>
68  class Event {
69  friend Sender;
70  public:
74  Event<Sender, EventArgs>(Sender &sender) : sender(sender), handlers() {
75  }
76 
77  size_t getAddress(std::function<void(Sender &, EventArgs &)> f) {
78  typedef void (fnType)(Sender &, EventArgs &);
79  fnType **fnPointer = f.template target<fnType *>();
80  if (fnPointer == NULL) return 0;
81  return (size_t) *fnPointer;
82  }
83 
85  void operator+=(function<void(Sender &sender, EventArgs &e)> handler) {
86  handlers.push_back(handler);
87  }
88 
89  void operator-=(function<void(Sender &sender, EventArgs &e)> handler) {
90  int handlerAddress = getAddress(handler);
91  if (handlerAddress == 0) // we can't get the function's address
92  {
93  return;
94  }
95 
96  int idx = -1;
97  for (int i = 0; i < handlers.size(); i++) {
98  if (handlerAddress == getAddress(handlers[i])) {
99  idx = i;
100  }
101  }
102 
103  if (idx >= 0)
104  handlers.erase(handlers.begin() + idx);
105  else
106  cerr << "Couldn't find an event handler to remove. Check your method's signature.";
107  }
108 
109  protected:
110  vector<function<void(Sender &sender, EventArgs &e)>> handlers;
111 
112  void invoke(EventArgs arg) {
113  for (auto pin1inputHandler : handlers) {
114  pin1inputHandler(sender, arg);
115  }
116  }
117 
118  Sender &sender;
119  };
120 }
121 
size_t getAddress(std::function< void(Sender &, EventArgs &)> f)
Definition: Event.h:77
Provides a simple C#-style observer pattern event queue.
Definition: Event.h:68
void operator-=(function< void(Sender &sender, EventArgs &e)> handler)
Definition: Event.h:89
void operator+=(function< void(Sender &sender, EventArgs &e)> handler)
Subscribe to an event.
Definition: Event.h:85
Definition: AdcPin.h:3