boost::lambda的实现模拟
http://www.cppblog.com/yindf/category/9614.html
//boost::lambda的实现模拟,只实现了加法和乘法。其他的可以继续扩充,不过lambda已经实现的很不错了
#include <algorithm>
#include <iostream>
using namespace std;
#define dim(x ) ( sizeof(x)/sizeof(x[0]) )
template<class Type>
struct add_action
{
Type add_data;
add_action(Type x):add_data(x){};
template<class T>
Type operator()(T x)
{
return add_data + x ;
}
};
template<class Type>
struct multiply_action
{
Type multiply_data;
multiply_action(Type x):multiply_data(x){};
template<class T>
Type operator()(T x)
{
return multiply_data * x ;
}
};
struct _1_class
{
template<class T>
add_action<T> operator+(T x)
{
return add_action<T>(x);
}
template<class T>
multiply_action<T> operator*(T x)
{
return multiply_action<T>( x );
}
};
_1_class _1 = _1_class();
int main(int argc, char* argv[])
{
int data[] = { 1,2,3,4,5,6,7,8,9,10};
int out[dim(data)]={0};
std::transform(data,data+dim(data) , out , _1 * 1.3 );
//_1*1.3将调用重载的operaotr*,将得到一个返回的临时函数对象,当前为multiply_action<double>(1.3)
//之后transform就使用这个临时对象进行操作。
std::copy( out , out+dim(out) ,ostream_iterator<int>(cout," ") );
cout<<endl;
return 0;
}