Skip to content

Instantly share code, notes, and snippets.

@melpon
Last active January 4, 2016 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melpon/8579444 to your computer and use it in GitHub Desktop.
Save melpon/8579444 to your computer and use it in GitHub Desktop.
#ifndef EVENT_HPP_INCLUDED
#define EVENT_HPP_INCLUDED
/*
使い方:
#include <iostream>
#include "event.hpp"
struct Listener {
event<void (int)> on_click;
event<void ()> on_press;
};
// イベント受信側
struct Receiver {
event_key key_ = make_event_key();
Receiver(Listener& ls) {
ls.on_click.push_back(key_, [](int n) {
std::cout << "on_click: " << n << std::endl;
});
ls.on_press.push_back(key_, []() {
std::cout << "on_press" << std::endl;
});
}
};
// イベント送信側
struct Sender {
Listener listener;
void do_click() {
listener.on_click(10);
}
};
int main() {
Sender sender;
Receiver receiver1(sender.listener);
Receiver receiver2(sender.listener);
sender.do_click();
}
*/
#include <functional>
#include <memory>
#include <algorithm>
typedef std::shared_ptr<void> event_key;
inline event_key make_event_key() { return event_key(new int()); }
template<class T>
class event;
template<class R, class... Args>
class event<R (Args...)> {
typedef std::function<R (Args...)> func_t;
typedef std::pair<std::weak_ptr<void>, func_t> pair_t;
std::vector<pair_t> fs_;
public:
template<class F>
void push_back(event_key key, F func) {
fs_.push_back(std::make_pair(std::weak_ptr<void>(std::move(key)), std::move(func)));
}
void erase_expired() {
fs_.erase(
std::remove_if(fs_.begin(), fs_.end(), [](const pair_t& p) { return p.first.expired(); }),
fs_.end());
}
void operator()(Args... args) {
erase_expired();
for (auto& p: fs_)
p.second(args...);
}
};
#endif // EVENT_HPP_INCLUDED
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment