Lambda表达式,QSharedPointer<>,std::function<>用法实例

Lambda表达式,QSharedPointer<>,std::function<>在Qt开发中用法实例

下面展示实例代码:

void TestLambdaFun(int extern_Param)
{
    enum RESULT{ SUCCCEED=0X00, POWERON_FAILURE=0X01,COMMUNICATION_FAILURE=0XFF};
     QSharedPointer<Timer *> SearchForwardRotationResultTimer = QSharedPointer<Timer *>(new Timer*(nullptr));

     std::function<void(int Test_times)> *pCirculaTestFun = new std::function<void(int Test_times)>; //循环测试次数
     QSharedPointer<std::function<void(int)>> CirculaTestFun(pCirculaTestFun);
      extern_Param = 1;
      *CirculaTestFun = [&,extern_Param,CirculaTestFun,SearchForwardRotationResultTimer](int Test_times)mutable{
		
		  extern_Param++;
          --Test_times;
          if(Test_times < 0)
          {
              return;
          }
          (*SearchForwardRotationResultTimer = new Timer(new QTimer,1000,false,[&,extern_Param,Test_times,SearchForwardRotationResultTimer,CirculaTestFun]{

                static int counts = 0;
                counts++;
                qDebug() << extern_Param << ":::::::"<< counts << "###" << Test_times<<endl;
                if(counts == 10)
                {
                    counts = 0;
                    (*SearchForwardRotationResultTimer)->stop();
                    (*SearchForwardRotationResultTimer)->deleteLater();

                    (*CirculaTestFun)(Test_times);  //开始测试
                }



          }));

          (*SearchForwardRotationResultTimer)->start();

          


      };


     (*CirculaTestFun)(10);//测试10次

}

代码解释。
在 void TestLambdaFun(int extern_Param)函数中,主要实现了循环测试功能流程Lambda函数CirculaTestFun ,在每次进入该函数后,先根据传进来的参数int Test_times进行次数递减以及对捕获的extern_Param值进行递增,然后对Test_times判断,如果该值小于0次,那么就不再执行下面的操作;如果大于等于0次,下面构建了一个定时器类对象,该定时器对象可以在每隔一秒进入

static int counts = 0;
counts++;
   qDebug() << extern_Param << ":::::::"<< counts << "###" << Test_times<<endl;
   if(counts == 10)
   {
       counts = 0;
       (*SearchForwardRotationResultTimer)->stop();
       (*SearchForwardRotationResultTimer)->deleteLater();

       (*CirculaTestFun)(Test_times);  //开始测试
   }

代码块执行一次流程操作。将int 类型的counts定义为static 静态变量,counts的作用域在上面块内一直存在,直到程序退出,打印 extern_Param、counts, Test_times值。当counts等于10时,将counts归零,并停止该定时器,然后删除掉该定制器,到这里,这个定时器操作过程结束。下一步 (*CirculaTestFun)(Test_times);开始新一轮的流程测试。其中用到了Lambda表达式知识、智能指针知识、函数模板知识、以及定时器封装类。如有任何疑问,欢迎留言互动。

该段代码已经放到Qt自建类里面进行测试,测试结果如下图:

程序调用TestLambdaFun(1)函数,输出开始
程序调用TestLambdaFun(1)函数,输出结束

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

九江在天

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

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

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

打赏作者

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

抵扣说明:

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

余额充值