boost bind 绑定一个带参数的虚函数?解决方案

boost bind 绑定一个带参数的虚函数?
本帖最后由 lhyxiaolang 于 2014-08-01 15:22:58 编辑
boost bind 绑定一个带参数的虚函数?
请问一下bind绑定有参数的虚函数的时候,怎么写?

class test 
{
public:
  virtual void test1(int a)
  {
    cout << "this is the class test" << a << endl;
  }

  virtual void test2()
  {
   cout << "this is the class test " << endl;
  }
}

class test_son : public test
{
  public:
  void test1(int a)
  {
    cout << "this is test1" << a << endl;
  }

   void test2() 
  {
    cout << "this is test2" << endl;
  }
};

void main()
{
test t;test_son son;
//绑定无参数
bind(&test::test2,_1) (son);
bind(&test::test2,_1) (t);
//绑定带参数
}

------解决方案--------------------

#include<iostream>
#include<functional>
using namespace std;
using namespace std::placeholders;

class test 
{
public:
  virtual void test1(int a)
  {
    cout << "this is the class test " << a << endl;
  }
 
  virtual void test2()
  {
   cout << "this is the class test " << endl;
  }
};
 
class test_son : public test
{
  public:
  void test1(int a)
  {
    cout << "this is test1 " << a << endl;
  }
 
   void test2() 
  {
    cout << "this is test2" << endl;
  }
};
 
int main()
{
test t;test_son son;
//绑定无参数
bind(&test::test2, _1)(son);
bind(&test::test2, _1)(t);
//绑定带参数
bind(&test::test1, _1, _2)(son, 5);
bind(&test::test1, _1, _2)(t, 6);
return 0;
}


g++编译运行成功,输出结果:

this is test2
this is the class test 
this is test1 5
this is the class test 6



------解决方案--------------------
引用:
谢谢,不晓得之前为什么没编译过,这次可以,在想问问如果我想写成:
function<void (int ) > ff = bind(&test::test1, _1, _2)这种形式,function<>改写成什么样




//绑定带参数
function<void(test_son,int)> f1 = bind(&test::test1, _1, _2);
function<void(test,int)> f2 = bind(&test::test1, _1, _2);
f1(son, 5);  // 调用
f2(t, 6);