我想了解下面的代码。
#include <iostream>
using std::cout;
template<int N> struct Fib {
enum { v = Fib<N - 1>::v + Fib<N - 2>::v };
};
template<> struct Fib<0> {
enum { v = 0 };
};
template<> struct Fib<1> {
enum { v = 1 };
};
int fib(int n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
int main() {
cout << Fib<46>::v << '\n';
// cout << fib(46) << '\n';
return 0;
}
它在编译时计算结果,没有任何明显的延迟。这是怎么做到的呢?如果我们调用fib(46),即使使用最快的PC也需要等待几秒钟。模板使用相同的计算方案,并使其瞬间完成。我还惊讶于使用模板生成的可执行文件大小几乎与不使用模板相同。我使用了GCC。