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中信号机制

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

worthsen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值