首页 > 解决方案 > C++ 在编译时评估 constexpr 模板数组值

问题描述

我在编译时创建了一个打包字符数组,但 c++ 告诉我表达式必须有一个常量值——不能评估不完整的“梯度<256U>”的值。

我正在尝试在我的代码中嵌入颜色渐变。

template<unsigned S>
struct gradient {
  constexpr gradient() : arr() {
    for (auto i = 0; i < S; i++)
      for (auto j = 0; j < S; j++)
        arr[i + j * S] = ((i % 256) << 24) | ((j % 256) << 16) | (((i * j) % 256) << 8) | 255;
  }

  unsigned arr[S * S];
};

constexpr auto g0 = gradient<255>(); // ok
constexpr auto g1 = gradient<256>(); // error
constexpr auto g2 = gradient<1024>(); // error

突然之间,我无法创建具有高于 255 的值的渐变结构。但是为什么呢?

标签: c++expressionconstantsconstexprcompile-time

解决方案


推荐阅读