【问题标题】:"function call must have a constant value in a constant expression"“函数调用必须在常量表达式中具有常量值”
【发布时间】:2016-02-10 16:31:54
【问题描述】:

我有以下代码:

constexpr unsigned long long power_function(const unsigned long long prime, const unsigned long long iterations) {
    return iterations > 0 ? prime * power_function(prime, iterations - 1) : prime;
}

/* Inside my Class Definition*/

private:
    static constexpr unsigned long long prime = power_function(-363, 1'000'000); //Error occurs here

IntelliSense 抱怨 power_function 使用不正确。但是对于我的生活,我无法解决问题所在。我正在使用 Visual Studio 2015,仅供参考。

错误信息:

Error   C2131   expression did not evaluate to a constant   Basic Server    c:\<snip>   28  
Error   C2131   expression did not evaluate to a constant   Basic Server    c:\<snip>   33  

第 28 行对应返回函数所在的行,第 33 行对应定义 constexpr 的行。

【问题讨论】:

  • 它可以编译吗?有时 IntelliSense 是错误的。
  • 显然有一个recursion limit in constexpr functions。输出窗口显示什么? (通常它比错误列表中显示的内容更多。)
  • @Cameron 我认为你是对的。如果我将其更改为 300 而不是 100 万,IntelliSense 仍然会抱怨,但编译错误消失了。
  • @KarolyHorvath 它解析为一个略小于1&lt;&lt;64 的数字。它恰好是一个素数,因此我使用它。
  • 点赞that

标签: c++ constexpr


【解决方案1】:

在 gcc 和 clang 编译器中,constexpr 的递归限制为 512。因为编译器将 constexpr 函数解释为内联函数(C++ 标准 7.1.5 subsec.2),所以必须在编译时解析它们。如果在 512 次迭代后编译器无法将表达式解析为常量,它会停止编译并引发错误。对于递归constexpr 函数调用,标准建议至少为 512,但不要求它(参见标准中的附件 B [implimits] 2.38)。

此限制可能适用于 Visual Studio,但我不确定。

【讨论】:

  • 不正确。该标准永远不会设定上限。 stackoverflow.com/questions/9258525/…
  • 你是对的。 512 限制在 gcc 和 clang 中实现。我认为这是标准中要求的,但它从来没有这么说。
  • gcc 和 clang 都允许使用此选项来增加递归深度:-fconstexpr-depth=&lt;value&gt;,但 Visual Studio 似乎不支持该选项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-14
  • 2016-09-22
相关资源
最近更新 更多