C++11 模板元编程初探: 在编译期间确定斐波那契数列

本文介绍了C++11中利用模板元编程技术在编译期间计算斐波那契数列的方法,讨论了递归展开的上限和编译器的溢出检查,以及这一思想在tuple使用上的应用,强调了C++语言设计的连贯性和优美性。
摘要由CSDN通过智能技术生成

虽然这种在编译时间确定的斐波那契数列不是那么好用,不过模板元编程的这种想法是非常重要的。

下面展示了一段通过模板元编程实现的(静态)编译期间确定的斐波那契额数列。

#include <iostream>
using namespace std;

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

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

template<>
struct fib<1>
{
    enum{ result=1};
};

int main()
{
    cout<<fib<1>::result<<endl;
    cout<<fib<2>::result<<endl;
    cout<<fib<3>::result<<endl;
    cout<<fib<4>::result<<endl;
    cout<<fib<5>::result<<endl;
    cout<<fib<6>::result<<endl;
    ///...
    cout<<fib<20>::result<<endl;

    return 0;
}

模板元求值会自动进行递归展开,由于递归的逻辑限制,必须确定递归终点,于是需要两个特化版本的fib结构体(否则会编译器就宕掉了)。

一般的编译器都会对这种

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值