标签:boost.lambda
// boost.lambda表达式用法
// made by davidsu33
// 2014-9-22
#include "stdafx.h"
#include <boost/typeof/typeof.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/bind/bind.hpp>
#include <boost/assign.hpp>
#include <boost/core/enable_if.hpp>
#include <vector>
#include <utility>
#include <memory>
#include <algorithm>
#include <cassert>
#include <iostream>
using namespace std;
//Boost的简单用法
void lambda_easy_use()
{
using namespace boost::assign;
vector<int> arr = list_of(0).repeat(19, 0);
int begin = 0;
for_each(arr.begin(), arr.end(),
(
boost::lambda::_1 = boost::lambda::var(begin)++,
boost::lambda::_1 += 10,
boost::lambda::_1 -= 5
)
);
for (unsigned i=0; i<arr.size(); ++i)
{
assert(arr[i] == 5+i);
}
cout<<"lambda_easy_use passed"<<endl;
}
//Boost的仿函数调用
void lambda_functors()
{
int i=10, j=20;
int r = (boost::lambda::_1 + boost::lambda::_2)(i,j);
assert(r == (i+j));
BOOST_AUTO(br, (boost::lambda::_1 - boost::lambda::_2)(i, j));
assert(br == (i-j));
//多次运算
BOOST_AUTO(br2,
(boost::lambda::_1 - boost::lambda::_2, boost::lambda::_1 += boost::lambda::constant(10))(i, j));
//??br2 == 20,br2的取值由第二个表达式赋予
assert(br2 == i);
assert(i == 20);
}
template<class T>
T fun(const T& value)
{
//要求输入值必须为整型
typedef boost::enable_if<boost::is_integral<T>, T>::type TType;
cout<<"fun is called!"<<endl;
cout<<"the value:"<<value<<endl;
return value+100;
}
void lambda_call()
{
vector<int> v;
using namespace boost::assign;
v += 1,2,4,8,16;
for_each(v.begin(), v.end(), fun<int>);
}
int _tmain(int argc, _TCHAR* argv[])
{
lambda_easy_use();
lambda_functors();
getchar();
return 0;
}
标签:boost.lambda
原文地址:http://blog.csdn.net/davidsu33/article/details/39483913