在编译时使用模板填充引用表

Populating reference tables at Compile Time using Templates

本文关键字:填充 引用 编译      更新时间:2023-10-16

我需要在编译时生成参考表,这样我可以节省一些运行时计算,说我有以下使用情况

static unsigned long long int table[21]={0,1,1};

template<long long N>
struct fib  
{
        static long long value()
        {
            fib<N-1>::value();
            table[N] = table[N-1] + table[N-2];         
        }
};
template<>
struct fib<0>
{
        static long long value()
        {
            return table[0];
        }
};
template<>
struct fib<1>
{
        static long long value()
        {
            return table[1];
        }
};

template<>
struct fib<2>
{
        static long long value()
        {
            return table[2];
        }
};

#include<iostream>
using namespace std;
int main()
{
    fib<20>::value();  // <<----  WARNING!
    for(int i=0 ;i <21 ; ++i)
        cout<<" "<<i<<":" << table[i];
    cout<<endl;
    return 0;   
}

结果是警告

fib .cpp:在static成员函数' static long long int fib::value() '中:fib .cpp:12:3:警告:函数中没有返回语句返回非void [- return-type]

是正确的

我的问题是,为什么没有人用这种方式,缺点?还有其他可能的方法吗?资源会很有帮助!

在模板结构中使用enum {value =}。例如,

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

template <int N>
struct Fibonacci
{
    static const long long value = Fibonacci<N-1>::value + Fibonacci<N-2>::value
};

这个链接可能会有帮助:在运行时获取模板元编程的编译时常量