Skip to content

Instantly share code, notes, and snippets.

@midned
Created March 14, 2015 23:16
Show Gist options
  • Save midned/0a06f576d2294b057c46 to your computer and use it in GitHub Desktop.
Save midned/0a06f576d2294b057c46 to your computer and use it in GitHub Desktop.
c++ signals
#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;
}
#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...);
};
#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