简体   繁体   English

“函数调用必须在常量表达式中具有常量值”

[英]“function call must have a constant value in a constant expression”

I have the following code: 我有以下代码:

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 complains that power_function is being used incorrectly. IntelliSense抱怨power_function使用不当。 But for the life of me, I can't work out what the issue is. 但对于我的生活,我无法弄清楚问题是什么。 I'm using Visual Studio 2015, FYI. 我正在使用Visual Studio 2015,仅供参考。

Error messages: 错误消息:

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  

line 28 corresponds to the line where the return function is, and line 33 corresponds to the line where the constexpr is defined. 第28行对应于返回函数所在的行,第33行对应于定义constexpr的行。

There is a recursion limit of 512 for constexpr in the gcc and clang compilers. gcc和clang编译器中constexpr的递归限制为512。 Because the compiler interprets constexpr functions as inline functions (C++ Standard 7.1.5 subsec. 2), they must be resolved at compile time. 因为编译器将constexpr函数解释为内联函数(C ++ Standard 7.1.5 subsec.2),所以它们必须在编译时解析。 If after 512 iterations the compiler cannot resolve the expression to a constant, it halts compilation and raises an error. 如果在512次迭代后编译器无法将表达式解析为常量,则会停止编译并引发错误。 The standard recommends a minimum of 512 for recursive constexpr function invocations, but does not require it (See Annex B [implimits] 2.38 in the standard). 该标准建议至少为递归constexpr函数调用512,但不要求它(参见标准中的附录B [implimits] 2.38)。

This limit may be applied in Visual Studio, but I am unsure. 此限制可能适用于Visual Studio,但我不确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM