【问题标题】:Populating reference tables at Compile Time using Templates在编译时使用模板填充参考表
【发布时间】:2015-10-09 04:33:14
【问题描述】:

我需要在编译时生成引用表,这样我就可以节省一些运行时计算,比如我有如下用例

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;   
}

导致警告

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

这是正确的。

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

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    在模板结构中使用枚举 {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
    };
    

    此链接可能会有所帮助: Getting template metaprogramming compile-time constants at runtime

    【讨论】:

    • 枚举默认为“int”,我打算处理更复杂的用例,这些用例对 char、指针和 long long 进行操作。所以在所有情况下使用枚举都无济于事:(
    • @Mahesh 考虑看看boost::mpl、boost::mpl::string 和static rational
    • @Mahesh 声明静态常量类型怎么样? (我刚刚添加)或在模板结构的构造函数中计算值不会发出警告。
    • @SangHeonLee 根据规范,这种类型的“静态”语句没有排序。我的意思是说 static const value = fib::value 后跟 static const valueRad = value % 10.
    • @Mahesh 好的,现在我明白你为什么需要这样的结果表了。 Finbonacci 的例子让我很困惑:(
    猜你喜欢
    • 2017-03-22
    • 2018-03-11
    • 2015-03-04
    • 2019-04-13
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    相关资源
    最近更新 更多