首页 / 软件开发 / C++ / Functional Programming与C++的模板元编程
Functional Programming与C++的模板元编程2010-05-24 cnblogs winter-cn先来看一个例子:#include <stdio.h>
template <int depth>
class Fibnacci
{
public:
static const int value = Fibnacci<depth-1>::value + Fibnacci<depth-2>::value;
};
template <>
class Fibnacci<0>
{
public:
static const int value = 0;
};
template <>
class Fibnacci<1>
{
public:
static const int value = 1;
};
template <int depth>
void printFibnacci()
{
printFibnacci<depth-1>();
wprintf(L"%d
", Fibnacci<depth>::value);
}
template <>
void printFibnacci<0>()
{
wprintf(L"%d
", Fibnacci<0>::value);
}
int main()
{
printFibnacci<8>();
return 0;
}
Fibnacci数列,相信是个程序员都能写出来,重点是,这个Fibnacci数列的计算完全是在编译时完成!后面的print也是如此,当你把参数调得很大时,运行时间不会有任何改变,但是你会花费长时间在编译阶段。如果你听说过一些模板元编程,你一定会知道"C++模板是图灵完备的"这个说法。模板元是如何图灵完备的?答案是,模板元跟Functional原理是一样的。模板的本质是定义与替换,lambda函数的本质也是定义与替换,这里的替换实际上符合的是数学中的lambda演算理论: