
この記事はかなり昔に執筆されており、誤りを含む場合があります。
C++において、Templateを使用しフィボナッチ数列を求める方法です。^^;)template<unsigned N> struct Fib { enum { Val = Fib<N - 1>::Val + Fib<N - 2>::Val }; }; template<> struct Fib<0> { enum { Val = 0 }; }; template<> struct Fib<1> { enum { Val = 1 }; };C++コード例
結果は以下の通り~~。#include <iostream> using namespace std; template<unsigned N> struct Fib { enum { Val = Fib<N - 1>::Val + Fib<N - 2>::Val }; }; template<> struct Fib<0> { enum { Val = 0 }; }; template<> struct Fib<1> { enum { Val = 1 }; }; int main() { cout << Fib<10>::Val << endl; return 0; }(※フィボナッチ数列の10番目の値は、55です。) うおっ、まぶしっ!!! いや~~、これはホント面白い技だなぁと思いました^^;) フィボナッチ数列自体は、まぁ正直どうでも良いんですが(笑)、 Templateの活用法は、まさに目からウロコ。 。 。 / / ポーン! ( Д ) 物理計算のエンジンを記述する等に、とても役立ちそうです。
