【问题标题】:Filling an std::array using math formula in compile time在编译时使用数学公式填充 std::array
【发布时间】: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


【解决方案1】:

这是一个不混淆的方法:将计算包装在一个函数中:

template <int N>
constexpr std::array<double, N> generate()
{
    std::array<double, N> arr{};
    for (int i = 0; i < N; ++i)
        arr[i] = complexFormula(i);
    return arr;
}

使用示例:

constexpr std::array<double, 10000> arr = generate<10000>();

(live demo)

这是因为,从 C++14 开始,在 constexpr 函数中允许循环,并且只要变量的生命周期在常量表达式的求值范围内开始,就可以修改变量。

【讨论】:

    猜你喜欢
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    相关资源
    最近更新 更多