constexpr関数fがあるとします。
constexpr int f(int x) { ... }
そして、コンパイル時に既知のconstintNがあります。
また
#define N ...;
また
const int N = ...;
あなたの答えによって必要に応じて。
int配列Xが欲しい:
int X[N] = { f(0), f(1), f(2), ..., f(N-1) }
関数がコンパイル時に評価され、Xのエントリがコンパイラによって計算され、結果がX初期化子リストで整数リテラルを使用した場合とまったく同じようにアプリケーションイメージの静的領域に配置されます。
これを書く方法はありますか?(たとえば、テンプレートやマクロなどを使用)
私が持っている最高のもの:(Flexoのおかげで)
#include <iostream>
#include <array>
using namespace std;
constexpr int N = 10;
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;
}