【发布时间】:2019-08-30 06:13:54
【问题描述】:
我想在编译时使用数学函数填充 constexpr std::array。是否可以通过简单的方式实现?
我找到了这个解决方案:C++11: Compile Time Calculation of Array。但是,还有其他仅使用 std 的现代解决方案吗?这对我来说似乎太混乱了。
int main()
{
// This is the array I need to fill
constexpr std::array<double, 100000> elements;
for (int i=0; i!=100000; ++i)
{
// Each element is calculated using its position with long exponential maths.
elements[i] = complexFormula(i); // complexFormula is constexpr
}
double anyVal = elements[43621];
// ...
}
【问题讨论】:
-
是的,它是一个 constexpr
-
另外,FWIW,
int可能不足以容纳100000。 -
@L.F.带有 16 位
int的编译器非常罕见 -
@AlanBirtles 稀有!= 不存在
标签: c++ arrays constexpr fill compile-time