在编译时使用模板填充引用表
Populating reference tables at Compile Time using Templates
我需要在编译时生成参考表,这样我可以节省一些运行时计算,说我有以下使用情况
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
};
这个链接可能会有帮助:在运行时获取模板元编程的编译时常量
相关文章:
- 将对象数组的引用传递给函数
- 在c++中用vector填充一个简单的动态数组
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 如何使用用户输入在C++中正确填充2D数组
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 如何找到大小'x'数组是否完全填充,在C++?
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 是使用按引用传递来填充容器更好,还是使用返回值来填充容器更好
- boost线程未填充通过引用传递的本地对象
- Visual C# - 引用 > 添加引用... > COM:该列表是如何填充的?
- 在编译时使用模板填充引用表
- 正确的方式来填充矢量传递的引用