Предположим, что у меня есть некоторая функция constexpr f:
constexpr int f(int x) { ... }
И у меня есть некоторая константа int N, известная во время компиляции:
Либо
#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;
}