// 忽略警告
#define _SCL_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#include <assert.h>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/ref.hpp>
#include <boost/assign/list_of.hpp>// list_of
using namespace boost;
using namespace std;
#include <algorithm>// for_each
int Plus(int a, int b)
{
return a + b;
}
struct demo
{
int add(int a, int b)
{
return a + b;
}
int operator()(int a) const
{
return a * a;
}
};
template<typename T>
struct summary
{
typedef void result_type;
T sum;
summary(T v = T()) :sum(v){}
void operator()(T const &x)
{
sum += x;
print(sum);
}
void print(T num){ cout << num * num << endl; }
};
// 用于回调
void call_back_print(int n)
{
cout << n << endl;
}
class call_back
{
private:
typedef boost::function<void(int)> Fun;
Fun fun;// 到时候用single2代替
int n;
public:
call_back(int a) :n(a){}
template<typename CallBack>
void accept(CallBack cb)
{
fun = cb;// 绑定回调函数
}
void run()
{
fun(n);// 执行
}
};
int main()
{
boost::function<int(int, int)> fun(Plus);// fun(&Plus)也可以,存储函数Plus
assert(fun);
cout << fun(2, 4) << endl;
fun = 0;// 等价fun.clear(); 清空function
assert(!fun);
try
{
fun(2, 4);
}
catch (boost::bad_function_call& e)
{
if (fun.empty())cout << "fun is empty!" << endl;// fun is empty!
cout << e.what() << endl;// call to empty boost::function
}
boost::function<int(demo&, int, int)> fun1 = boost::bind(&demo::add, _1, _2, _3);// 函数声明时指定绑定类型 和 函数
cout << fun1(demo(), 4, 5) << endl;// 9
demo d;
boost::function<int(int, int)> fun2 = boost::bind(&demo::add, &d, _1, _2);// 在bind时绑定demo的实例 和 函数
cout << fun2(4, 5) << endl;// 9
// 引用
boost::function<int(int)> fun3 = boost::cref(d);// 包装对象的引用
cout << fun3(10) << endl;// 100
vector<int> v = (assign::list_of(1), 2, 3, 4, 5, 6, 7, 8, 9, 10);
summary<int> s;
boost::function<void(int const&)> fun4(boost::ref(s));
for_each(v.begin(), v.end(), fun4);// std 1^2 (1+2)^2 (1+2+3)^2 ...
cout << s.sum << endl;// 55
// 回调
call_back cb(100);
cb.accept(call_back_print);// 绑定
cb.run();// 100
cb.accept(boost::bind(&summary<int>::print,s,_1));// 绑定
cb.run();// 10000
cb.accept(boost::ref(s));// sum = 55
cb.run();// (55 +100)^2
return 0;
}