简体   繁体   中英

“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. But for the life of me, I can't work out what the issue is. I'm using Visual Studio 2015, FYI.

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.

There is a recursion limit of 512 for constexpr in the gcc and clang compilers. Because the compiler interprets constexpr functions as inline functions (C++ Standard 7.1.5 subsec. 2), they must be resolved at compile time. If after 512 iterations the compiler cannot resolve the expression to a constant, it halts compilation and raises an error. 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).

This limit may be applied in Visual Studio, but I am unsure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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