■
ついでにC++版
#include<map> template<typename T>struct fix:T{}; template<typename T> struct memo:T{ std::map<int,int>memo_; int operator()(int n){ std::map<int,int>::iterator it = memo_.find(n); if(it != memo_.end())return it->second; int value = T::operator()(n); return memo_[n] = value; } }; template<typename T> struct debug_print : T{ int operator()(int n){ printf("in (%d)\n",n); int value = T::operator()(n); printf("out(%d) = %d\n",n,value); return value; } }; struct fib{ virtual int operator()(int n){ if(n<=1)return 1; else return (*this)(n-1) + (*this)(n-2); } }; #include<stdio.h> int main(){ memo<debug_print<fix<fib> > >f; printf("%d\n",f(35)); }
ここまで書いてこのプログラムの構造がデザインパターンで言う所のデコレータパターンであることに気づく。
もっと早く気づけばよかった...orz