8 #ifndef Sawyer_Callbacks_H
9 #define Sawyer_Callbacks_H
11 #include <Sawyer/Sawyer.h>
12 #include <Sawyer/SharedPointer.h>
18 template<
class Callback>
21 typedef std::list<Callback> CbList;
25 bool isEmpty()
const {
26 return callbacks_.empty();
30 return callbacks_.size() == other.callbacks_.size() &&
31 std::equal(callbacks_.begin(), callbacks_.end(), other.callbacks_.begin());
34 Callbacks& append(
const Callback &callback) {
35 callbacks_.push_back(callback);
40 callbacks_.insert(callbacks_.end(), other.callbacks_.begin(), other.callbacks_.end());
44 Callbacks& prepend(
const Callback &callback) {
45 callbacks_.push_front(callback);
49 Callback& prepend(
const Callbacks &other) {
50 callbacks_.insert(callbacks_.begin(), other.callbacks_.begin(), other.callbacks_.end());
54 Callbacks& eraseFirst(
const Callback &callback) {
55 for (
typename CbList::iterator iter=callbacks_.begin(); iter!=callbacks_.end(); ++iter) {
56 if (*iter == callback) {
57 callbacks_.erase(iter);
64 Callbacks& eraseLast(
const Callback &callback) {
65 for (
typename CbList::reverse_iterator reverseIter=callbacks_.rbegin(); reverseIter!=callbacks_.rend(); ++reverseIter) {
66 if (*reverseIter == callback) {
67 typename CbList::iterator forwardIter = (++reverseIter).base();
68 callbacks_.erase(forwardIter);
75 Callbacks& eraseMatching(
const Callback &callback) {
76 typename CbList::iterator iter = callbacks_.begin();
77 while (iter!=callbacks_.end()) {
78 if (*iter == callback) {
79 typename CbList::iterator toErase = iter++;
80 callbacks_.erase(toErase);
87 template<
class CB,
class Args>
88 bool applyCallback(CB *callback,
bool chained, Args &args)
const {
89 return (*callback)(chained, args);
92 template<
class CB,
class Args>
93 bool applyCallback(
const SharedPointer<CB> &callback,
bool chained, Args &args)
const {
94 return (*callback)(chained, args);
97 #if __cplusplus >= 201103ul
98 template<
class CB,
class Args>
99 bool applyCallback(
const std::shared_ptr<CB> &callback,
bool chained, Args &args)
const {
100 return (*callback)(chained, args);
104 template<
class CB,
class Args>
105 bool applyCallback(CB &callback,
bool chained, Args &args)
const {
106 return callback(chained, args);
109 template<
class Arguments>
110 bool apply(
bool chained,
const Arguments &arguments)
const {
111 for (
typename CbList::const_iterator iter=callbacks_.begin(); iter!=callbacks_.end(); ++iter)
112 chained = applyCallback(*iter, chained, arguments);
116 template<
class Arguments>
117 bool apply(
bool chained, Arguments &arguments)
const {
118 for (
typename CbList::const_iterator iter=callbacks_.begin(); iter!=callbacks_.end(); ++iter)
119 chained = applyCallback(*iter, chained, arguments);
124 template<
class Callback>
130 : callbacks_(callbacks), callback_(callback) {
131 callbacks_.append(callback);
135 callbacks_.eraseLast(callback_);