Unix/C++--libsigc++深入理解
1 简介
- 信号槽是观察者模式的一种实现,或者说是一种升华。
- 信号槽这一术语最初来自 Trolltech 公司的 Qt 库。并成为Qt中最核心功能模块。
- 不用Qt情况下,常用的信号与槽的库有三种:boost的signals,sigslot,sigc++。
- sigslot优点是不用担心空回调,当回调对象析构时会自动disconnect
且支持多线程,线程安全,有锁,缺点是只能回调void类型函数,不支持返回值。boost中的signals库架构类似,支持返回值,但引入了boost中的其他库。且slot没有优先级,不能动态调整回调队列中的先后顺序。 - libsigc++是一个callback的完整包装,Bjarne Stroustrup都对libsigc++大为推荐。
- 其中用了很多C++11的特性,有的是C++14的特性,如std::decay_t。
2 核心思想
2.1 介绍
2.2 回调
#include <iostream>
#include <string.h>
class UIcallBack
{
public:
virtual void onAppActivated() = 0;
virtual void onShowMore() = 0;
};
class UIManager
{
public:
UIManager() {}
~UIManager() {}
void setCallBack(UIcallBack *pcallBack)
{
m_pcallBack = pcallBack;
}
UIcallBack *m_pcallBack;
};
class AppManager : public UIcallBack
{
public:
AppManager() {}
~AppManager() {}
void onAppActivated();
void onShowMore();
UIManager uiManager;
};
void AppManager::onAppActivated()
{
;
}
void AppManager::onShowMore()
{
std::cout << "show\n" << std::endl;
}
int main()
{
AppManager app;
UIManager ui;
ui.setCallBack(&app);
ui.m_pcallBack->onShowMore();
}
3 用例
3.1 回调函数为一般函数
#include <iostream>
#include <string>
#include <sigc++/sigc++.h>
//! 普通函数
void Print(const std::string& str)
{
std::cout << str;
}
int main()
{
//! 返回值void,参数const std::string&
sigc::signal<void, const std::string&> signal_print;
//! 链接函数
signal_print.connect( sigc::ptr_fun(&Print));
//! 发射信号
signal_print.emit("hello world\n");
system("pause");
return 0;
}
3.2 回调函数为成员函数
#include <iostream>
#include <string>
#include <sigc++/sigc++.h>
class Printer :public sigc::trackable
{
public:
void Work(){slot.emit("work\n");}
typedef sigc::signal<void, const std::string&> Slot;
Slot slot;
void Print(const std::string& str){std::cout<<str;}
};
int main()
{
Printer printer;
Printer::Slot::iterator iter = printer.slot.connect(sigc::mem_fun(&printer,&Printer::Print));
printer.Work();
iter->disconnect();
printer.Work();
system("pause");
return 0;
}
4 功能模块分析
sigc::ptr_fun负责绑定一般函数
sigc::men_fun负责绑定成员函数.
5 编译报错
Qt中 explicit temp_slot_list (slot_list& slots) : slots_(slots)
explicit temp_slot_list (slot_list& slots) : slots_(slots)
参考
1、Unix/C+±-信号与槽机制的理解
2、libsigcplusplus–github
3、使用sigc++插槽系统
4、 explicit temp_slot_list (slot_list& slots) : slots_(slots)
5、回调函数实现类似QT中信号机制