1.Boost:bind
#include
<iostream>
#include
<boost/bind.hpp>
using
namespace
std;
using
namespace
boost;
int
f(int
a,
int
b = 12)
{
return
a +
b;
}
int
g(int
a,
int
b,
int
c)
{
return
a +
b +
c;
}
int
main(int
argc,
char *argv[])
{
//通过下面方法调用等价于f(1,2);
cout <<
"bind(f, 1, 2)() = " <<bind(f,
1, 2)() << endl;
//同样能够绑定部分参数,例如:下方表示第二个参数传递的是15
cout <<
"bind(f, 12, _1)(15) = " <<bind(f,
12, _1)(15) <<
endl;
//用两个占位符
cout <<
"bind(f, _1, _2)(1, 3) = " <<bind(f,
_1,
_2)(1, 3) <<
endl;
cout <<
"----------" <<
endl;
//引入参数调用的方式
int
i = 5;
cout <<
"bind(f, i, _1)(1) = " <<
bind(f,
i,
_1)(1) <<
endl;
cout <<
"----------" <<
endl;
//等价于g(1,2,3)
cout <<
"bind(g, 1, 2, 3)() = " <<bind(g,
1, 2, 3)()<< endl;
//用三个占位符的情况
cout <<
"bind(g,_1,_2,_3)(2,3,4) = " <<
bind(g,_1,_2,_3)(2,3,4)
<< endl;
cin.get();
return 0;
}
运行结果:
2.boost案例1
#include
<iostream>
#include
<string>
#include
<boost/bind.hpp>
#include
<vector>
#include
<algorithm>
#include
<functional>
using
namespace
std;
using
namespace
boost;
//绑定函数的默认值,继承二进制函数类的所有内容
class
add :public
std::binary_function<int,
int,
void>
{
public:
void operator()(int
i,
int
j)
const
{
std::cout
<< i +
j <<
std::endl;
}
};
void
add(int
i,
int
j)
{
std::cout
<< i +
j <<
std::endl;
}
void
main()
{
vector<int>
myv;
myv.push_back(11);
myv.push_back(23);
myv.push_back(34);
for_each(myv.begin(),
myv.end(),
bind(add,
13, _1));
cin.get();
}
运行结果:
3bind并不仅仅限于方法,下面的例子是绑定结构体的情况。
#include
<iostream>
#include
<boost/bind.hpp>
#include
<algorithm>
#include
<cassert>
using
namespace
std;
using
namespace
boost;
struct
F
{
int operator()(int
a,
int
b){
return
a -
b; };
bool operator()(long
a,
long
b){
return
a ==
b; };
};
struct
F2
{
int
s;
typedef
void
result_type;
void operator()(int
x)
{
s +=
x;
std::cout
<< "x = " <<
x <<"
s = "<<
s <<
std::endl;
}
};
int
main(int
argc,char
*argv[])
{
F
f;
int
x = 104;
//通过:bind<R>(f, ...)
这种语法,但是
cout <<
"bind<int>(f, _1, _2)(10,5) = " <<bind<int>(f,
_1,
_2)(10,5) <<
endl;
cout <<
"---------" <<
endl;
//通过:boost::bind(boost::type<R>(),f,_1,_2)(x,y);的方式进行绑定
cout <<
"boost::bind(boost::type<int>(), f, _1, 3)(8)= "<<boost::bind(boost::type<int>(),
f,
_1, 3)(8) <<
endl;
F2
f2 = { 0 };
int
a[] = { 1, 2, 3 };
cout <<
"---------" <<
endl;
//for_each是#include <algorithm>中的
for_each(a,
a + 3,
bind(std::ref(f2),
_1));
//下面的是#include <cassert>头文件中的
//assert(f2.s == 6);
cin.get();
return 0;
}
运行结果: