首页 > 其他 > 详细

Boost 信号与槽 使用

时间:2020-09-24 23:16:01      阅读:162      评论:0      收藏:0      [点我收藏+]

 

test1

#if 1

/*
  参考blog   https://www.cnblogs.com/jiayayao/p/6246161.html   

Qt异步的实现实际上是将信号push到一个队列中,然后由统一的线程来处理信号对应的槽函数而已。
Boost的信号/槽在信号被触发时,槽函数只能是同步执行,没有像Qt那样的异步接口。
当然也可以根据这个原理自己封装带异步的信号/槽机制,不过那样的话应该需要另外开启线程了。

*/
#include <iostream>
#include <boost/signals2.hpp>
#include <boost/bind.hpp>

using namespace std;
using namespace boost::signals2;

void slots1()
{
    cout<<"slots111111111 called"<<endl;
}
void slots2()
{
    cout<<"slots222222222 called"<<endl;
}
class A
{
public:
    static int staticMemberFunc(int param)
    {
        cout<<"A::staticMemberFunc called, param: "<<param<<endl;
        return 11+param;
    }
    int memberFunc(int param)
    {
        cout<<"A::memberFunc called, param: "<<param<<endl;
        return 6+param;
    }
};
int main()
{
    boost::signals2::signal<void()>   sig;
    boost::signals2::signal<int(int)> sig2;

    A a;

    // --------- sig() test -----------------
    connection c1 = sig.connect(&slots1);
    connection c2 = sig.connect(&slots2);
    cout<<"First call-------------------"<<endl;
    sig();

    if (c2.connected())
    {
        c2.disconnect();
    }
    cout<<"Second call-------------------"<<endl;
    sig();


    // -------- sig2() test ---------------
    connection c3 =sig2.connect(&A::staticMemberFunc);               // 绑定静态成员函数  -----这是 1 处

    connection c4 =sig2.connect(boost::bind(&A::memberFunc, &a, _1));// 绑定成员函数
    // bind 使用 ,参考BLOG : https://www.cnblogs.com/benxintuzi/p/4862129.html   

    cout << "------test1---------: " << endl; 
    sig2(44);

    cout << "------test2---------: " << endl; 
    cout << *sig2(44) << endl; // 只能返回最后被调用的插槽的返回值
    
    //cout << sig2(44) << endl;  编译报错  , 猜测是不是和连接参数是指针 有关系
    //    于是我们来进行test3  
    cout << "------test3 --------: " << endl; 
    boost::signals2::signal<int(int)> sig3;  
    connection c5 =sig3.connect(A::staticMemberFunc);               // 绑定静态成员函数   -----这是 2处
    sig3(55);
    cout << *sig3(55) << endl; // 只能返回最后被调用的插槽的返回值           //              -----这是 3处

    // 实测 1 2 处,加不加取地址,都无所谓。 但是3处一定要加*符号。

    return 0;
}

#endif

 

 

 

 

.

Boost 信号与槽 使用

原文:https://www.cnblogs.com/happybirthdaytoyou/p/13726924.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!