Skip to content

Instantly share code, notes, and snippets.

@Quinny

Quinny/signal.h Secret

Last active March 6, 2022 19:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Quinny/aa2ed2189a3c4209b50f to your computer and use it in GitHub Desktop.
Save Quinny/aa2ed2189a3c4209b50f to your computer and use it in GitHub Desktop.
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