相关疑难解决方法(0)

C++ 11:编译数组的时间计算

假设我有一些constexpr函数f:

constexpr int f(int x) { ... }
Run Code Online (Sandbox Code Playgroud)

我在编译时知道一些const int N:

#define N ...;
Run Code Online (Sandbox Code Playgroud)

要么

const int N = ...;
Run Code Online (Sandbox Code Playgroud)

根据你的答案需要.

我想要一个int数组X:

int X[N] = { f(0), f(1), f(2), ..., f(N-1) }
Run Code Online (Sandbox Code Playgroud)

这样在编译时评估函数,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 …
Run Code Online (Sandbox Code Playgroud)

c++ templates constexpr c++11

40
推荐指数
1
解决办法
8372
查看次数

标签 统计

c++ ×1

c++11 ×1

constexpr ×1

templates ×1