Created
March 14, 2015 23:16
-
-
Save midned/0a06f576d2294b057c46 to your computer and use it in GitHub Desktop.
c++ signals
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 <iostream> | |
#include "Signal.h" | |
#include "Signal.cpp" // I don't like this | |
int main(int argc, char* argv[]) { | |
Signal<int, int> on_click; | |
on_click.connect([](int a, int b) { | |
std::cout << "A: " << a << " | B: " << b << std::endl; | |
}); | |
on_click.trigger(2, 3); // same as on_click(2, 3) | |
return 0; | |
} |
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> | |
#include "Signal.h" | |
template<typename ...Arguments> | |
void Signal<Arguments...>::connect(std::function<void (Arguments...)> listener) { | |
listeners.push_back(listener); | |
} | |
template<typename ...Arguments> | |
void Signal<Arguments...>::trigger(Arguments... args) { | |
for (auto &listener : listeners) { | |
listener(args...); | |
} | |
} | |
template<typename ...Arguments> | |
inline void Signal<Arguments...>::operator ()(Arguments... args){ | |
trigger(args...); | |
}; |
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
#pragma once | |
#include <vector> | |
#include <functional> | |
template<typename ...Arguments> | |
class Signal { | |
public: | |
void connect(std::function<void (Arguments...)> listener); | |
void trigger(Arguments... args); | |
inline void operator ()(Arguments... args); | |
private: | |
std::vector<std::function<void (Arguments...)>> listeners; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment