【发布时间】:2016-09-09 14:57:02
【问题描述】:
假设我们有这样的代码。它运行良好,可以预先计算前 5 个斐波那契数。
#include <iostream>
template <int T>
struct fib;
template <>
struct fib<0>{
constexpr static int value = 1;
};
template <>
struct fib<1>{
constexpr static int value = 1;
};
template <int I>
struct fib{
constexpr static int value = fib<I - 1>::value + fib<I - 2>::value;
};
int main(){
std::cout << fib<0>::value << std::endl;
std::cout << fib<1>::value << std::endl;
std::cout << fib<2>::value << std::endl;
std::cout << fib<3>::value << std::endl;
std::cout << fib<4>::value << std::endl;
std::cout << fib<5>::value << std::endl;
}
但是它有一个“小”问题。
如果我们需要将它用于编译时未知的值怎么办?
对于少数几个值,我们可以这样做:
const int max = 5;
int getData(){
return 5; // return value between 0 and max.
}
int something(){
switch(getData()){
case 0: return fib<0>::value;
case 1: return fib<1>::value;
case 2: return fib<2>::value;
case 3: return fib<3>::value;
case 4: return fib<4>::value;
case 5: return fib<5>::value;
}
}
这适用于 5 个值,但如果我们有 150 或 300 个值怎么办?
改300行的代码真的不是很严重...
这里有什么解决方法?
【问题讨论】:
-
您可以创建一个静态数组并在运行时按照 e 查找。 G。 stackoverflow.com/questions/37297359/…
标签: c++ c++11 templates template-meta-programming template-specialization