-
-
Save Quinny/aa2ed2189a3c4209b50f to your computer and use it in GitHub Desktop.
signals and slots in c++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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...); | |
} | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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