虽然这种在编译时间确定的斐波那契数列不是那么好用,不过模板元编程的这种想法是非常重要的。
下面展示了一段通过模板元编程实现的(静态)编译期间确定的斐波那契额数列。
#include <iostream>
using namespace std;
template<int num>
struct fib
{
enum {result=fib<num-1>::result+fib<num-2>::result};
};
template<>
struct fib<0>
{
enum {result=1};
};
template<>
struct fib<1>
{
enum{ result=1};
};
int main()
{
cout<<fib<1>::result<<endl;
cout<<fib<2>::result<<endl;
cout<<fib<3>::result<<endl;
cout<<fib<4>::result<<endl;
cout<<fib<5>::result<<endl;
cout<<fib<6>::result<<endl;
///...
cout<<fib<20>::result<<endl;
return 0;
}
模板元求值会自动进行递归展开,由于递归的逻辑限制,必须确定递归终点,于是需要两个特化版本的fib结构体(否则会编译器就宕掉了)。
一般的编译器都会对这种