最近学习C++11的variadic template argument,终于可以摆脱用fpmacro模板来复制一大堆代码的做法了,好开心。这个例子的main函数用lambda写了一个斐波那契数列的递归计算函数。跟以往不同的是,在Y函数的帮助下,这个lambda表达是可以成功看到自己,然后递归调用。当然这仍然需要用普通的C++递归来实现,并不是λ-calculus那个高大上的Y Combinator。
#include
<functional>
#include
<memory>
#include
<iostream>
#include
<string>
using
namespace std;
template<typename
TResult, typename ...TArgs>
class
YBuilder
{
private:
function<TResult(function<TResult(TArgs...)>, TArgs...)> partialLambda;
public:
YBuilder(function<TResult(function<TResult(TArgs...)>, TArgs...)> _partialLambda)
:partialLambda(_partialLambda)
{
}
TResult operator()(TArgs ...args)const
{
return partialLambda(
[this](TArgs ...args)
{
return
this->operator()(args...);
}, args...);
}
};
template<typename
TMethod>
struct
PartialLambdaTypeRetriver
{
typedef
void
FunctionType;
typedef
void
LambdaType;
typedef
void
YBuilderType;
};
template<typename
TClass, typename
TResult, typename ...TArgs>
struct
PartialLambdaTypeRetriver<TResult(__thiscall
TClass::*)(function<TResult(TArgs...)>, TArgs...)>
{
typedef
TResult
FunctionType(TArgs...);
typedef
TResult
LambdaType(function<TResult(TArgs...)>, TArgs...);
typedef
YBuilder<TResult, TArgs...> YBuilderType;
};
template<typename
TClass, typename
TResult, typename ...TArgs>
struct
PartialLambdaTypeRetriver<TResult(__thiscall
TClass::*)(function<TResult(TArgs...)>, TArgs...)const>
{
typedef
TResult
FunctionType(TArgs...);
typedef
TResult
LambdaType(function<TResult(TArgs...)>, TArgs...);
typedef
YBuilder<TResult, TArgs...> YBuilderType;
};
template<typename
TLambda>
function<typename
PartialLambdaTypeRetriver<decltype(&TLambda::operator())>::FunctionType> Y(TLambda
partialLambda)
{
return
typename
PartialLambdaTypeRetriver<decltype(&TLambda::operator())>::YBuilderType(partialLambda);
}
int
_tmain(int
argc, _TCHAR* argv[])
{
auto fib = Y([](function<int(int)> self, int
index)
{
return
index<2
?1
:self(index-1)+self(index-2);
});
for (int i = 0; i < 10; i++)
{
cout << fib(i) << " ";
}
cout << endl;
}
posted on 2014-02-28 08:34
陈梓瀚(vczh) 阅读(11017)
评论(3) 编辑 收藏 引用 所属分类:
C++实用技巧