consteval
函数的参数是:
[Andrew Sutton在他的论文Translation and evaluation: A mental model for compile-time metaprogramming中解释了这种行为的动机,如this SO post所指出。
您可以从consteval
函数返回参数并将其用作constexpr
:
consteval int foo(int n) {
return n;
}
constexpr int i = foo(9);
但是您不能在constexpr
函数本身内部将其用作consteval
:
// fails to compile
consteval int abs(int n) {
if constexpr (n < 0) {
return -n;
}
else {
return n;
}
}
以上编译失败,因为n是not一个constexpr
。
您当然可以使用简单的if,它将在编译时进行评估:
// compiles
consteval int abs(int n) {
if (n < 0) {
return -n;
}
else {
return n;
}
}
constexpr int i = -9;
constexpr int num = abs(i);
这是一个[[术语问题:
是否有一个普遍使用的名称,它是在编译时是已知的],但是不是常量表达式?
consteval函数的参数是:在编译时是已知的,但不是constexpr。此行为的动机由Andrew Sutton在他的论文《翻译和评估:A ...