本文是lambda分析篇最重要的一篇。lambda源码比较庞大(把宏全部展开),只是对其中的小部分进行分析,小部分足以展示其难度和运行机理。
boost源码给我的感觉对基础知识要求很高,是对知识正确的运用(我们的朋友们已经走向了另一条路,喜马拉雅上还是要从中国这方爬比较合适)。lambda源码对模板技术的运用很高,比其它代码如pool,shared_ptr等等都要厉害。总体来看mpl源码是元编程的皎皎者,但是很难运用在实际的工作中。lambda应该是实际运用的出色者。
先看下面的代码:
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include "boost/lambda/lambda.hpp"
#include "boost/tuple/tuple.hpp"
//#include "boost/lambda/bind.hpp" // Tuple to cons mapper --------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
using namespace boost::lambda;
using namespace std;
boost::tuple<int,double,string> triple(42, 3.245, "The amazing tuple!");
int a0 = triple.get<0>();
double a1 = triple.get<1>();
string a2 = triple.get<2>();
std::vector<int> vec(3);
vec[0] = 12;
vec[1] = 10;
vec[2] = 7;
//Transform using a lambda expression
std::for_each(vec.begin(), vec.end(), std::cout<<_1);
std::for_each(vec.begin(), vec.end(), std::cout<<_1<<' ');
//std::transform(vec.begin(), vec.end(), vec.begin(), _1-= 4); return 0; }
首先,主要研究lambda的运用:
std::for_each(vec.begin(), vec.end(), std::cout<<_1);
打印出容器中的元素,这些元素显然是连续的。如果要分开,可以写成:
std::cout<<_1<<' ' 或是std::cout<<_1<<std::endl;
简单的增加了后面的' '或是std::endl将使模板参数变得异常的复杂。
因此,先考虑不那么复杂的语句:
std::cout<<_1
上面语句一定先要展开_1,这个在源码中被定义成这样的形式:
boost::lambda::placeholder1_type& _1 = free1;
boost::lambda::placeholder1_type free1 = boost::lambda::placeholder1_type();
typedef const lambda_functor<placeholder<FIRST> > placeholder1_type;
template <int I> struct placeholder;
template<>