假設我們有這樣的代碼。它運作良好,並預先計算出前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。 http://stackoverflow.com/questions/37297359/sequence-array-initialization-with-template – xcvii