Skip to content

Instantly share code, notes, and snippets.

@mbains
Forked from munro/signals.cpp
Created March 22, 2012 23:01
Show Gist options
  • Save mbains/2165307 to your computer and use it in GitHub Desktop.
Save mbains/2165307 to your computer and use it in GitHub Desktop.
C++11 Signals
#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
@frigge
Copy link

frigge commented Jan 5, 2013

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment