几段纠结的C++代码,求解脱~
最近接触些函数式编程语言,后来想起来C++好像在某个方面也支持函数式“编程”,于是找资料~ 记忆中好像有过一本书叫做什么来着~呃 哦对了,叫做《C 语言 什么来着~》作者是...谁来着??
不说这些了,我说到哪里了?哦对了,最近接触了些函数式编程语言,没事自己在C++也捣鼓了一番。这下面的几段代码是捣鼓出来了,可有根像刺一样的刺就像刺在了肉里,纠结,特冒雨上来求解脱:
首先下面是两个类似 D&A的《C++ Template Meta Programing》里面所说的“元函数类”的类,是为接着下来的类做准备的:
// Factorial Gstruct G {private: template <typename f, int n> struct Meta { const static unsigned __int64 Value = n * f::Apply<n - 1>::Value; }; template <typename f> struct Meta<f,1> { const static unsigned __int64 Value = 1 ; };public: template<typename _f> struct Apply { struct Type { template <int _n> struct Apply { typedef Meta<_f,_n> Type; const static unsigned __int64 Value = Type::Value; }; }; };};// Fibonacci Gstruct G2 {private: template <typename self,int n> struct Meta { const static unsigned __int64 Value = self::Apply<n -1>::Value + self::Apply<n -2>::Value; }; template <typename self> struct Meta<self,1> { const static unsigned __int64 Value = 1; }; template <typename self> struct Meta<self,0> { const static unsigned __int64 Value = 0; };public: template <typename _self> struct Apply { struct Type { template <int _n> struct Apply { typedef Meta<_self,_n> Type; const static unsigned __int64 Value = Type::Value; }; }; };}; template< typename T1,typename T2,typename T3,typename T4 /* ... */ > struct TMFunction { }; template TMFucntion1 = TMFunction <Type1>; auto a = sizeof (TMFucntion1<Type2,Type3,Type4>); template TMFucntion2 = TMFunction <Type1,Type2>; auto b = sizeof (TMFucntion2<Type3,Type4>); template TMFucntion3 = TMFunction <Type1><Type2><Type3>; auto c = sizeof (TMFucntion3<Type4>); auto d = sizeof (TMFunction <Type1> <Type2> <Type3> <Type4>);template<typename G>struct Y { struct W { template <typename F> struct Apply { typedef typename F::Apply<F>::Type Type; }; }; struct F { template<typename f> struct Apply { // 下面这两行代码(#1,#2)不能通过编译,因为这时 F::Apply<>::Type 还没有定义, // 所以不能递归地用于G::Apply<>::Type 的定义 /* typedef typename W::Apply<f>::Type t; //#1 typedef typename G::Apply<t>::Type Type; //#2 */ // 只能以下面的办法来解决 // 这里 “Type”的定义 并不依赖于 "G::Apply<>::Type",所以 "G::Apply<>::Type" 使用它不会构成递归定义 // 但是这使得Y失去了通用性,因为"Type"必须再重复"G::Apply<>::Type" 的定义 /**/ struct Type { template< int n> struct Apply { typedef typename W::Apply<f>::Type t; //temp t typedef typename G::Apply<t>::Type::Apply<n>::Type Type; const static unsigned __int64 Value = Type::Value; }; }; /**/ }; }; // the result is here typedef typename W::Apply<F>::Type Type;};