boost::bind 用法

#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>

class Test
{
  public:
    void test()
    {
      std::cout<<"test"<<std::endl;    
    }
    void test1(int i)
    {
      std::cout<<"test1:"<<i<<std::endl;
    }
    void test2(int a,int b)
    {
      std::cout<<"test2:a:"<<a<<" b:"<<b<<std::endl;
    }
};
int main()
{
  Test t;
  boost::function<void()> f1; // 无参数,无返回值
  f1 = boost::bind(&Test::test, &t);
  f1(); //调用t.test();
  
  f1 = boost::bind(&Test::test1, &t, 2);
  f1(); // 调用 t.test1(2);
    
  boost::function<void(int)> f2;
  f2 = boost::bind(&Test::test1,&t,_1);
  f2(3);  //调用t.test1(3)
  
  boost::function<void(Test*)> f3;
  f3 = boost::bind(&Test::test1, _1,4);
  f3(&t); //调用t.test1(4)
  
  boost::bind(&Test::test2, _1,5,6)(&t);    //test2:a:5 b:6
  boost::bind(&Test::test2, &t,_1,8)(7);    //test2:a:7 b:8
  boost::bind(&Test::test2, &t,_1,_2)(9,10);  //test2:a:9 b:10
  boost::bind(&Test::test2, &t,11,_1)(12);    //test2:a:11 b:12
  return 0;
}

posted @ 2010-10-22 08:50  海畅  阅读(626)  评论(0编辑  收藏  举报