簡體   English   中英

“函數調用必須在常量表達式中具有常量值”

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

我有以下代碼:

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的行。

gcc和clang編譯器中constexpr的遞歸限制為512。 因為編譯器將constexpr函數解釋為內聯函數(C ++ Standard 7.1.5 subsec.2),所以它們必須在編譯時解析。 如果在512次迭代后編譯器無法將表達式解析為常量,則會停止編譯並引發錯誤。 該標准建議至少為遞歸constexpr函數調用512,但不要求它(參見標准中的附錄B [implimits] 2.38)。

此限制可能適用於Visual Studio,但我不確定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM