我是靠谱客的博主 快乐招牌,这篇文章主要介绍C++模板编程:如何在编译器确定斐波那契数列?,现在分享给大家,希望可以做个参考。

使用模板元技术:

template <int num> struct Fibonacci { enum { result = Fibonacci<num-1>::result + Fibonacci<num-2>::result }; };

我们可以看到,上面实际上运用到了递归,递归总要有一个结束的时候,因此我们需要为它写两个特化版本:

template<> struct Fibonacci<0> { enum { result = 1 }; }; template<> struct Fibonacci<1> { enum { result = 1 }; };

这样,我们就可以在编译器确定斐波那契数列的具体值了,下面是一个测试程序:

int _tmain(int argc, _TCHAR* argv[]) { printf("%d ", (int)(Fibonacci<0>::result)); printf("%d ", (int)(Fibonacci<1>::result)); printf("%d ", (int)(Fibonacci<2>::result)); printf("%d ", (int)(Fibonacci<3>::result)); printf("%d ", (int)(Fibonacci<4>::result)); printf("%d/n", (int)(Fibonacci<5>::result)); return 0; }

输出结果是:

1 1 2 3 5 8

最后

以上就是快乐招牌最近收集整理的关于C++模板编程:如何在编译器确定斐波那契数列?的全部内容,更多相关C++模板编程:如何在编译器确定斐波那契数列内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(104)

评论列表共有 0 条评论

立即
投稿
返回
顶部