template 的递归调用问题
2012-01-13 16:30
246 查看
Fibonacci 的 template 使用:
1. Function Method
方法一:
下面这段代码会报错:template instantiation depth exceeds maximum of 1024 ....
方法二:
下面则正确
为什么方法一编译会出错??
也许解释为:template为"编译期间"展开,而如果if语句的值判断在“运行期”才生效的话,那么编译器展开template时则没有==1 or ==2 的判断条件了!
2.Struct Method
1. Function Method
方法一:
下面这段代码会报错:template instantiation depth exceeds maximum of 1024 ....
template< int N > int fibonacci( ) { if ( N == 1 ) return 1; else if ( N == 2 ) return 1; else return N + fibonacci< N-1 >(); }
方法二:
下面则正确
template< int N > int fibonacci( ) { return fibonacci< N -1 >() + fibonacci< N-2 >(); } template< > int fibonacci< 2 >( ) { return 1; } template< > int fibonacci< 1 >( ) { return 1; }
为什么方法一编译会出错??
也许解释为:template为"编译期间"展开,而如果if语句的值判断在“运行期”才生效的话,那么编译器展开template时则没有==1 or ==2 的判断条件了!
2.Struct Method
相关文章推荐
- 递归调用过多导致的栈溢出问题说明
- <C语言>用递归调用函数解决穷举n位二进制数问题
- 递归调用,汉诺塔问题
- 递归调用里的性能问题(js)
- 递归、函数的调用机制及汉诺塔问题
- 函数递归调用问题
- 在model中递归调用model本身时的死循环问题。
- C语言学习4: 函数返回值与传入参数,关于函数值传递和类型隐性转换,变量不同的作用域,static变量,多文件编译例如两个C文件,显示函数调用语句跳转,递归,斐波那契数列,多文件编译相同变量的问题。
- 递归、函数的调用机制及汉诺塔问题
- 记一次递归调用问题
- 数据结构基础(6)--递归和函数调用--汉诺塔问题C语言实现
- keil中函数递归调用问题
- 递归问题 --自己调用自己
- DBUnit单元测试用restTemplate调用接口出现unrecognized token verifyFail:was expection('true','false' or 'null')问题
- 用C语言解决(hanoi)汉诺塔问题——函数的递归调用
- 使用函数的递归调用来解决Hanoi(汉诺)塔问题。
- 小问题,对递归重复调用的改进,一起来分享
- 由反序列化二叉树实现函数引起的二叉树节点递归调用问题
- 汉诺塔问题与递归调用
- 全排列问题(递归调用)