您可以在constexpr中使用constexpr对象
但是您不能在constexpr中使用consteval。
为什么?
我认为consteval应该是某种“狭窄”的constexpr。
请帮助我从这种设计中理解。
constexpr int constexpr_sqr(int n) { return n*n; }
consteval int consteval_sqr(int n) { return n*n; }
constexpr int constexpr_sqr2(int n) {
// not allowed
// return consteval_sqr(n);
// not allowed
// constexpr imm = consteval_sqr(n);
// return imm;
return constexpr_sqr(n);
}
int main() {
// while can do this
constexpr auto imm = consteval_sqr(999);
}
[LIVE]
最佳答案
这是争论。 constexpr
函数不需要进行常量评估。这意味着n
在常量表达式中不可用。
I thought consteval should have been some kind of "narrow" constexpr.
不,这些只是必须不断求值的函数。这意味着它们的参数必须始终在常量表达式中可用。
您可以使用在常量表达式中不可用的参数来调用
constexpr
函数,只要您不在需要常量表达式的上下文中,它的格式仍然正确。
关于c++ - 当您可以从consteval函数创建constexpr对象时,为什么constexpr函数不能消耗consteval函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63393278/