Skip to content

Instantly share code, notes, and snippets.

@Quinny

Quinny/signal.h Secret

Last active Feb 15, 2016
Embed
What would you like to do?
signals and slots in c++
#include <vector>
#include <functional>
namespace qp {
template <typename ...Args>
using delegate = std::function<void(Args...)>;
template <typename ...Args>
class signal {
private:
using fn_t = delegate<Args...>;
std::vector<fn_t> observers;
public:
void connect(fn_t f) {
observers.push_back(f);
}
void operator ()(Args... a) {
for (auto i: observers)
i(a...);
}
};
}
#include "signal.h"
#include <string>
#include <iostream>
#include <functional>
struct button {
qp::signal<std::string> update;
void click() {
update("clicked!");
}
};
struct label {
std::string text;
void changeText(std::string s) {
text = s;
std::cout << s << std::endl;
}
};
int main() {
using namespace std::placeholders;
label label1;
label label2;
button button1;
button1
.update
.connect(std::bind(&label::changeText, std::ref(label1), _1));
// or
// button1.update.connect([&](std::string s) { label1.changeText(s); });
button1
.update
.connect(std::bind(&label::changeText, std::ref(label2), _1));
button1.click();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.