boost::bind应用示例

[cpp] view plain copy
 
  1. // testBind.cpp : Defines the entry point for the console application.  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5.   
  6. #include <boost/bind.hpp>  
  7. #include <boost/function.hpp>  
  8.   
  9. #include <assert.h>  
  10. #include <iostream>  
  11.   
  12. /* 
  13.   Title:boost::bind应用示例 
  14.   示例运行环境: 
  15.       [1]boost 1.39 SDK 
  16.       [2]VisualStudio2008 + SP1 
  17.   示例内容: 
  18.       Precondition:MySubClass实例方法 参数方法列表 已知 
  19.       Do:控制权从MyParentClass实例方法,转移到,MySubClass实例方法。 
  20. */  
  21.   
  22.   
  23. //MyDataType:自定义数据类型  
  24. struct MyDataType{  
  25.     MyDataType() {}  
  26.     MyDataType(int nV):m_nV(nV) {}  
  27.     int m_nV;  
  28. };  
  29.   
  30. //MyParentClass:框架Class,负责消息派发  
  31. class MyParentClass{  
  32. public:  
  33.     boost::function<int(int,MyDataType)> m_fSub;  
  34.   
  35.     int CallSubClassFunc(int nDT,MyDataType mdtDT)  
  36.     {  
  37.         int nR = m_fSub(nDT,mdtDT);  
  38.         return nR;  
  39.     }  
  40. };  
  41.   
  42. //MySubClass:业务逻辑层,负责消息处理  
  43. class MySubClass{  
  44. public:  
  45.     int Run(int nDT,MyDataType mdtDT)  
  46.     {  
  47.         return nDT+mdtDT.m_nV;        
  48.     }  
  49. };  
  50.   
  51.   
  52. int _tmain(int argc, _TCHAR* argv[])  
  53. {  
  54.     MyParentClass mpc;  
  55.     MySubClass msc;  
  56.       
  57.     //两种实例方法间,建立联系  
  58.     mpc.m_fSub=boost::bind<int>(&MySubClass::Run,msc,_1,_2);  
  59.       
  60.     //触发调用  
  61.     int nR=mpc.CallSubClassFunc(2,MyDataType(3));  
  62.   
  63.     assert(nR==5);  
  64.       
  65.     return 0;  
  66. }  

http://blog.csdn.net/lee353086/article/details/5269910

原文地址:https://www.cnblogs.com/findumars/p/7635920.html