学习Boost中的lambda表达式库,下面是一些简单的示例:
#include <iostream>
#include <typeinfo>
#include <vector>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/switch.hpp>
#include <boost/lambda/exceptions.hpp>
#include <boost/assign/list_of.hpp>
using namespace std;
using namespace boost;
class Foo
{
public:
Foo(int cnt = 0):count(cnt)
{
}
void setCount(int cnt)
{
if(cnt < 0)
{
throw FooCountException(cnt);
}
this->count = cnt;
}
int getCount()
{
return this->count;
}
~Foo()
{
}
struct FooCountException
{
FooCountException(int cnt)
{
cout<<"Foo Count Set Error !!! Foo Count "<<cnt<<" little than zero !!!"<<endl;
}
};
private:
int count;
};
void func(int a,float b,double c)
{
cout<<"a = "<<a<<" ; b = "<<b<<" ; c = "<<c<<" ;"<<endl;
}
int main()
{
using namespace boost::lambda;
int i=3;
int j=2;
int k = 0;
k = (_1 + _2)(i,j);
//cout<<typeid(_1).name()<<endl;
//cout<<typeid((_1 + _2)).name()<<endl;
cout<<"Result : "<<k<<endl;
(_1 = 5, _1 + ref(i))(i);
cout<<"New i value : "<<i<<endl;
int a = 1;
(_1+=2)(a);
cout<<"New a value : "<<a<<endl;
int b = 2;
(_1+=ref(_2))(a,b);
cout<<"Final a value : "<<a<<endl;
int array[] = {1,2,3,4,5,6,7};
int curr_val = 0;
curr_val = (_1[_2])(array,4);
cout<<"Currl Index Value : "<<curr_val<<endl;
Foo * fo = new Foo(10);
(fo->setCount((_1 * _2)(2,3)));
cout<<"Test1 Count : " << (fo->getCount())<<endl;
typedef void (Foo::*setfun)(int);
typedef int (Foo::*getfun)();
setfun my_setCnt = &Foo::setCount;
getfun my_getCnt = &Foo::getCount;
(fo->*my_setCnt)((_1 - _2)((fo->*my_getCnt)(),1));
cout<<"Test2 Count : " << ((fo->*my_getCnt)()) <<endl;
//cout<<""<<(fo->*my_getCnt());
bind(func,_1,_2,_3)(123,3.14f,-103.245);
bind(static_cast< void (*)(int,float,double) >(&func), _1,_2,_3)(123,3.14f,-103.245);
bind(&Foo::setCount,&(*fo),_1)(6);
cout<<"Test3 Count : " << fo->getCount() <<endl;
using namespace boost::assign;
const vector<int> nums = list_of(2)(4)(3)(6)(9)(13);
cout<<"-------------------------"<<endl;
for_each(nums.begin(),nums.end(),(switch_statement(_1,
case_statement<2>(cout<<constant("two")),
case_statement<6>(cout<<constant("six")),
case_statement<9>(cout<<constant("nine")),
default_statement(cout<<constant("other:"))
),
cout<<constant("\n")
) );
Foo fo2;
try_catch(
bind(&Foo::setCount,&fo2,_1),
catch_exception<Foo::FooCountException>(
cout << constant("Exception Throwed !!!")
),
catch_exception<std::exception>(
cout << constant("Std Exception !!!")
),
catch_all(
(cout << constant("Unknown"), rethrow())
)
)(-2);
cout<<"Curr Count : "<<fo2.getCount()<<endl;
//
return 0;
}