-
-
Save mbains/2165307 to your computer and use it in GitHub Desktop.
C++11 Signals
This file contains hidden or 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
#ifndef __signals_h__ | |
#define __signals_h__ | |
#include <list> | |
#include <memory> | |
#include <iostream> | |
#include <functional> | |
namespace signals { | |
template<typename... Values> class Signal { | |
private: | |
std::list<std::function<void(Values...)>> fns; | |
public: | |
void bind(std::function<void(Values...)> fn) { | |
fns.push_back(fn); | |
} | |
void trigger(Values... values) { | |
for (auto it = fns.begin(); it != fns.end(); ++it) { | |
(*it)(values...); | |
} | |
} | |
}; | |
} | |
// Example | |
signals::Signal<int, int> onEvent; | |
onEvent.bind([](int a, int b) { | |
std::cout << "Event triggered " << a << ", " << b << "\n"; | |
}); | |
onEvent.trigger(10, 20); | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice little signal handler ... i've considered writing something like that myself and googling for inspiration I stumbled upon your solution. Just one little critic: Given that you use std::list and c++11 features anyway I'd rather write the for loop as:
for (auto fn : fns) fn(values...);
makes it a lot more compact and readable.