c++ - 当您可以从consteval函数创建constexpr对象时,为什么constexpr函数不能消耗consteval函数?

标签 c++ constexpr c++20 consteval

您可以在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/

相关文章:

c++ - 在 COM 接口(interface)的 Vtable 中查找特定函数的索引

c# - 如何在 Windows 中获取和设置系统音量

c++ - 将字符串数组从C++ DLL返回到VBA(Excel)

c++ - 如何在编译时获得多维 std::vector 的深度?

c++ - 非 constexpr 类的 Constexpr 方法

c++ - 我们可以在 c++20 协程中使用 alloca() 或可变长度数组扩展吗?

c++ - cmake/make 在 mac os x 10.6 snow leopard 下使用 g++4.2

c++ - constexpr 函数向数组添加一个整数

c++ - 从常量表达式中有符号整数的溢出中删除未定义的行为?

c++ - std::span 构造函数、libcxx 与 libstdc++、模板与非模板?