boost bind 绑定一个带参数的虚函数?解决方案
boost bind 绑定一个带参数的虚函数?
boost bind 绑定一个带参数的虚函数?
请问一下bind绑定有参数的虚函数的时候,怎么写?
------解决方案--------------------
g++编译运行成功,输出结果:
------解决方案--------------------
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(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);