您的位置:首页 > 其它

boost::bind 与 boost::function 的使用方法例子

2014-02-17 00:00 302 查看
摘要: boost中的bind与function是一个非常有用的工具,这里写个示例

啥也不说,直接看代码:

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

using namespace boost;
using namespace std;

int f(int a, int b)
{
return a + b;
}

int g(int a, int b, int c)
{
return a + b * c;
}

class Point
{
public:
Point(int x, int y) : _x(x), _y(y) {}
void print(const char *msg) {
cout << msg << "x=" << _x << ", y=" << _y << endl;
}
private:
int _x, _y;
};

int main()
{
//! f 有多少个参数,f 后面就要跟多少个参数。如果不明确的,用占位符
cout << bind(f, 2, 3)() << endl;    // ==> f(2, 3)
cout << bind(f, 12, _1) (5) << endl;   // ==> f(12, 5),其中参数b为不明确参数
cout << bind(g, _2, _1, 3) (3, 5) << endl;  // ==> g(5, 3, 3) 注意顺序

Point p(11, 34);
Point &rp = p;
Point *pp = &p;

bind(&Point::print, p, "Point: ") ();
//   ^              ^
// 注意,为表示Point::print为成员函数,成员函数前面要加&区分。
// 对象可以为实例、引用、指针
bind(&Point::print, rp, "Reference: ") ();  //! 引用
bind(&Point::print, pp, _1) ("Pointer: ");  //! 指针
bind(&Point::print, _1, _2) (p, "As parameter: ");  //! 对象也可以用占位符暂时代替

//! function的类型定义与需要的参数有关
function<void ()> func0 = bind(&Point::print, p, "func0: ");
function<void (const char *)> func1 = bind(&Point::print, pp, _1);

func0();    //! function对象的调用
func1("func1: ");

return 0;
}


一般情况下,bind 与 function 配合使用。

bind与function还可以将类型完成不同的函数(成员函数与非成员函数)包装成统一的函数调用接口。如下示例:

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

using namespace boost;
using namespace std;

class Point
{
public:
Point(int x, int y) : _x(x), _y(y) {}
void print(string msg) {
cout << msg << "x=" << _x << ", y=" << _y << endl;
}
private:
int _x, _y;
};

class Person
{
public:
Person(string name, int age) : _name(name), _age(age) {}
void sayHello() {
cout << "Hello, my name is " << _name << ", my age is : " << _age << endl;
}
private:
string _name;
int _age;
};

void printSum(int limit)
{
int sum = 0;
for (int i = 0; i < limit; ++i) {
sum += i;
}
cout << "sum = " << sum << endl;
}

void doAll(vector<function<void ()> > &funcs)
{
for (size_t i = 0; i < funcs.size(); ++i) {
funcs[i] ();
}
}

int main()
{
vector<function<void ()> > funcList;

Person john("John", 23);
funcList.push_back(bind(&Person::sayHello, john));

Point p1(23, 19);
funcList.push_back(bind(&Point::print, p1, "Point: "));

funcList.push_back(bind(printSum, 20));

doAll(funcList);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: