boost::lambda的实现模拟

本文模拟实现了Boost.Lambda库中的部分功能,仅限于加法和乘法操作,并通过示例展示了如何使用这些功能来处理整数数组。该实现提供了一个简单的模板类,用于定义加法和乘法行为。

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值