constexpr
和consteval
有什么区别吗?
consteval int x1 = 2;
constexpr int x2 = 5;
使用 constexpr 比 consteval 更好吗?
标准实际上说:
consteval 说明符仅适用于函数或函数模板的声明。
所以你的第一个示例不应该编译。
但是,您可以将
consteval
或 constexpr
放在函数上:
constexpr int foo (int x) { return x; }
consteval int bar (int x) { return x; }
constexpr
当应用于函数时,consteval
是强制性的 - 它告诉编译器,如果无法在编译时评估此函数调用,则会生成错误。