【问题标题】:How come constexpr functions can not consume consteval functions while you can create constexpr objects from consteval functions?为什么 constexpr 函数不能使用 consteval 函数,而您可以从 consteval 函数创建 constexpr 对象?
【发布时间】:2020-12-03 04:35:26
【问题描述】:

你可以在 consteval 中使用 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]

【问题讨论】:

  • 因为函数参数从来都不是常量表达式

标签: c++ constexpr c++20 consteval


【解决方案1】:

这是争论。 constexpr 函数不需要持续评估。这意味着n 不能用于常量表达式。

我认为 consteval 应该是某种“狭义”的 constexpr。

不,这些只是必须不断评估的函数。这意味着它们的参数必须始终在常量表达式中可用。

您可以使用在常量表达式中不可用的参数调用constexpr 函数,只要您不在需要常量表达式的上下文中,它仍然是格式正确的。

【讨论】:

  • 啊... consteval 简单地折叠了 constexpr 函数的“叠加”。
猜你喜欢
  • 2021-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-31
  • 2021-10-26
  • 2016-12-15
  • 1970-01-01
  • 2022-12-21
相关资源
最近更新 更多