一種實現C++ 11數組的方法,該數組的元素通過編譯器計算其索引的函數進行初始化,並將結果存儲在數據段中應用程序圖像的(.RODATA)如下使用模板,部分特和constexpr:C++ 11:具有對數評估深度的編譯時數組
error: constexpr evaluation depth exceeds maximum of 512
這是因爲:
#include <iostream>
#include <array>
using namespace std;
constexpr int N = 1000000;
constexpr int f(int x) { return x*2; }
typedef array<int, N> A;
template<int... i> constexpr A fs() { return A{{ f(i)... }}; }
template<int...> struct S;
template<int... i> struct S<0,i...>
{ static constexpr A gs() { return fs<0,i...>(); } };
template<int i, int... j> struct S<i,j...>
{ static constexpr A gs() { return S<i-1,i,j...>::gs(); } };
constexpr auto X = S<N-1>::gs();
int main()
{
cout << X[3] << endl;
}
這並不適用於大的N值的工作頭尾樣式的遞歸模板評估,它具有線性深度N的有效值。
有沒有辦法做到這樣的評估深度是對數的N而不是線性? (並且因此將避免默認深度限制)
相關:http://stackoverflow.com/questions/12108390/c11-compile-time-calculation-of-array –
相關:http://stackoverflow.com/questions/13102996/c11-workaround-use-of -this-incomplete-type-error –