【问题标题】:consteval vs constexpr on variablesconsteval vs constexpr 变量
【发布时间】:2021-01-31 08:34:40
【问题描述】:

constexpr 和 consteval 有什么区别吗?

 consteval int x1 = 2;
 constexpr int x2 = 5;

使用 constexpr 比使用 consteval 更好吗?

【问题讨论】:

  • 我已经回滚了这个问题,因为它在下面得到了很好的回答。如果您愿意,请提出一个新问题,否则您最终可能会浪费其他人的时间来写答案,这并不理想。

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


【解决方案1】:

standard 实际上说:

consteval 说明符只能应用于函数或函数模板的声明。

所以你的第一个例子should not compile。


但是,您可以将consteval 或constexpr 放在函数上:

constexpr int foo (int x) { return x; }
consteval int bar (int x) { return x; }

constexpr 应用于函数时只是主要是建议性的(参见 Davis Herring 的评论)——它告诉编译器,如果可以的话,在编译时评估这个函数调用。

另一方面,consteval 是强制性的 - 它告诉编译器,如果您无法在编译时评估此函数调用,则会生成错误。

Live demo

【讨论】:

  • constexpr 在函数上不是建议性的,因为能够将其返回值用作模板参数“需要”编译时评估(ie,除了对于口译员)。
猜你喜欢
  • 2012-11-01
  • 2016-07-24
  • 2015-05-04
  • 2020-12-03
  • 1970-01-01
  • 2021-02-20
  • 1970-01-01
  • 1970-01-01
  • 2020-10-08
相关资源
最近更新 更多