boost function相当于函数指针,通过bind函数去绑定一个函数和一个对象以及参数。
如:
boost::function f1; // 此处参数为空,返回值为空
boost::function f2; //此处参数为int和string,返回值类型为int
class Foo
{
public:
void methodA();
void methodInt(int a);
};
class Bar
{
public:
void methodB();
};
Foo foo;
f1 = boost::bind(&Foo::methodA, &foo);
f1(); // 调用 foo.methodA();
Bar bar;
f1 = boost::bind(&Bar::methodB, &bar);
f1(); // 调用 bar.methodB();
f1 = boost::bind(&Foo::methodInt, &foo, 42);
f1(); // 调用 foo.methodInt(42);
boost::function f2; // int 参数,无返回值
f2 = boost::bind(&Foo::methodInt, &foo, _1);
f2(53); // 调用 foo.methodInt(53);
-
#include <boost/function.hpp>
-
#include <boost/bind.hpp>
-
#include <iostream>
-
-
using namespace std;
-
-
-
class TestA
-
{
-
public:
-
void method()
-
{
-
cout<<"TestA: method: no arguments"<<endl;
-
}
-
-
void method(int a, int b)
-
{
-
cout<<"TestA: method: with arguments"
-
<<"value of a is: "<<a
-
<<" value of b is "<<b <<endl;
-
}
-
};
-
-
-
void sum(int a, int b)
-
{
-
int sum = a + b;
-
cout<<"sum: "<<sum<<endl;
-
}
-
-
int main()
-
{
-
boost::function<void()> f;
-
boost::function<void(int, int)> e;
-
TestA test;
-
-
f = boost::bind(&TestA::method, &test);
-
f();
-
-
f = boost::bind(&TestA::method, &test, 1, 2);
-
f();
-
-
e = boost::bind(&TestA::method, &test, 1, _2); //注意如果参数前面加了下划线,则表示该参数可以替换。
-
e(3,5);
-
-
f = boost::bind(&sum, 1, 2);
-
f();
-
}
打印值:
TestA: method: no arguments
TestA: method: with argumentsvalue of a is: 1 value of b is 2
TestA: method: with argumentsvalue of a is :1 value of b is 5
sum: 3
阅读(1709) | 评论(0) | 转发(0) |