Recently learn c++11 variadic template argument, finally can get rid of the Fpmacro template to copy a lot of code of practice, good fun. The main function of this example uses lambda to write a recursive computational function of a Fibonacci sequence. Unlike in the past, with the help of the Y function, this lambda expression is able to see itself successfully and then recursively called. Of course this still needs to use the ordinary C + + recursive return realization, is not λ-calculus that tall on the Y Combinator.
#include <functional> #include <memory> #include <iostream> #include <string> using namespace St
D Template<typename TResult, TypeName ... Targs> class Ybuilder {Private:function<tresult (Function<tresult (Targs ...) ", Targs ...)
> Partiallambda; Public:ybuilder (Function<tresult) (Function<tresult (Targs ...) ", Targs ...) > _partiallambda):p artiallambda (_PARTIALLAMBDA) {} TResult operator () (Targs ... args) const {RET
Urn 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::o Perator ()) >::FunctionType> Y (Tlambda partiallambda) {return typename Partiallambdatyperetriver<decltype (& Amp
Tlambda::operator ()) >::ybuildertype (PARTIALLAMBDA); int _tmain (int argc, _tchar* argv[]) {Auto fib = Y ([] (function<int (int) > self, int index) {retur N index<2 1:self (index-1) +sElf (index-2);
});
for (int i = 0; i < i++) {cout << fib (i) << "";
} cout << Endl; }