[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
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; }
相关文章推荐
- c++第三次实验
- C语言基础篇(2):按位比较是否相等、找出不是成对出现的单数、不用中间变量实现两个数的交换
- c++第三次上机实验-个人所得税计算器
- c语言中的字节数关系、
- 浅谈C++容器(六)
- 浅谈C++容器(二)
- 浅谈C++容器(一)
- 第3周 C语言及程序设计初步例程-47 小小型应用系统开发指导(二)
- C++第3次作业
- C++问题小结--1.命名空间namespace应用举例
- C++实验3-多分数段函数求值
- 【c++】挑7
- C++学习笔记十三 - C++宏替换认识大小写区分
- 关于C语言的输入输出重定向
- c++实验3-分段函数求值
- 史上最详细c语言学生管理系统(完整的源代码)
- c++上机第三次实验
- C++ 指针 引用 const
- C++作业3
- 【c++】合唱队问题