您的位置:首页 > 其它

template 的递归调用问题

2012-01-13 16:30 246 查看
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 的判断条件了!

2.Struct Method
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: