您的位置:首页 > 编程语言 > C语言/C++

[c++] C++11 Signals and Slots

2016-04-11 21:48 351 查看
http://simmesimme.github.io/tutorials/2015/09/20/signal-slot/
https://en.wikipedia.org/wiki/Signals_and_slots
to install gcc-5 in ubuntu, type : apt-get install gcc-5 g++-5

#ifndef SIGNAL_HPP
#define SIGNAL_HPP

#include <functional>
#include <map>

// A signal object may call multiple slots with the
// same signature. You can connect functions to the signal
// which will be called when the emit() method on the
// signal object is invoked. Any argument passed to emit()
// will be passed to the given functions.

template <typename... Args>
class Signal {

public:

Signal() : current_id_(0) {}

// copy creates new signal
Signal(Signal const& other) : current_id_(0) {}

// connects a member function of a given object to this Signal
template <typename F, typename... A>
int connect_member(F&& f, A&& ... a) const {
slots_.insert({++current_id_, std::bind(f, a...)});
return current_id_;
}

// connects a std::function to the signal. The returned
// value can be used to disconnect the function again
int connect(std::function<void(Args...)> const& slot) const {
slots_.insert(std::make_pair(++current_id_, slot));
return current_id_;
}

// disconnects a previously connected function
void disconnect(int id) const {
slots_.erase(id);
}

// disconnects all previously connected functions
void disconnect_all() const {
slots_.clear();
}

// calls all connected functions
void emit(Args... p) {
for(auto it : slots_) {
it.second(p...);
}
}

// assignment creates new Signal
Signal& operator=(Signal const& other) {
disconnect_all();
}

private:
mutable std::map<int, std::function<void(Args...)>> slots_;
mutable int current_id_;
};

#endif /* SIGNAL_HPP */


#include "Signal.hpp"
#include <iostream>

int main() {

// create new signal
Signal<std::string, int> signal;

// attach a slot
signal.connect([](std::string arg1, int arg2) {
std::cout << arg1 << " " << arg2 << std::endl;
});

signal.emit("The answer:", 42);

return 0;
}


#include "Signal.hpp"
#include <iostream>

class Button {
public:
Signal<> on_click;
};

class Message {
public:
void display() const {
std::cout << "Hello World!" << std::endl;
}
};

int main() {
Button  button;
Message message;

button.on_click.connect_member(&Message::display, message);
button.on_click.emit();

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: