Fibonacci 的 template 使用:
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 的判断条件了!