作为Comate,由文心一言驱动的智能编程助手,我很乐意帮你解答关于“error: call to non-'constexpr' function”的问题。下面是对你的问题的详细回答: 1. 解释'constexpr'的含义 constexpr是C++11引入的一个关键字,用于指示函数或变量可以在编译时求值。如果一个函数被声明为constexpr,那么它的所有参数都必须
constexpr int f5(int x) { // Error, function body contains more than if (x<0) // return statement. x = -x; return x; } 将函数模板声明为constexpr函数时,如果实例化导致函数不满足constexpr函数的需求,那么将忽略constexpr说明符。 例如: template <class C> constexpr NL f6(C c) { // ...
exp2(x * x, n /2) : exp2(x * x, (n -1) /2) * x; }// Compile-time computation of array lengthtemplate<typenameT,intN>constexprintlength(constT(&)[N]){returnN; }// Recursive constexpr functionconstexprintfac(intn){returnn ==1?1: n * fac(n -1); }// User-defined ...
constexpr int mf = 20; // 20 is a constant expression constexpr int limit = mf + 1; // mf + 1 is a constant expression constexpr int sz = size(); // ok only if size is a constexpr function ---虽然不能使用普通函数作为constexpr变量的初始化式,但我们将看到,新标准允许将某些函数...
Can a constexpr function call a non-constexpr function? The answer is yes, but only when the constexpr function is being evaluated in a non-constant context. A non-constexpr function may not be called when a constexpr function is evaluating in a constant context (because then the constexp...
constexpr int f5(int x) { // Error, function body contains more than if (x<0) // return statement. x = -x; return x; } When a function template is declared as aconstexprfunction, if the instantiation results in a function that does not satisfy the requirements of aconstexprfunction...
constexpr函数(constexpr function)是指能用于常量表达式的函数。定义constexpr函数的方法与其他函数类似,不过要遵循几项约定:函数的返回类型及所有形参的类型都得是字面值类型,而且函数体中必须有且只有一条return语句: constexprintnew_sz() {return42;}
intN>constexprintlength(constT(&)[N]){returnN;}// Recursive constexpr functionconstexprintfac(...
Aconstexpr functionis a function that is allowed to be called in a constant expression. To make a function a constexpr function, we simply use theconstexprkeyword in front of the function’s return type. Key insight Theconstexprkeyword is used to signal to the compiler and other developers...
其中用 constexpr function 替代模板进行编译期计算可以说是现代 C++ 最重要的改进之一了。 constexpr 本身其实并不难以理解,非常直观。但是由于几乎每个 C++ 版本都在改进它,所以不同的 C++ 版本可以使用的内容差别很大,有时候可能给人一种inconsistency的感觉。