【发布时间】:2020-08-29 19:02:00
【问题描述】:
consteval 函数的参数是:
- 某种 在编译时已知
- 但 不是 constexpr
Andrew Sutton 在他的论文 Translation and evaluation: A mental model for compile-time metaprogramming 中解释了这种行为背后的动机,this SO post 指出了这一点。
您可以从consteval 函数返回参数并将其用作constexpr:
consteval int foo(int n) {
return n;
}
constexpr int i = foo(9);
但你不能在 consteval 函数本身中将它用作 constexpr:
// fails to compile
consteval int abs(int n) {
if constexpr (n < 0) {
return -n;
}
else {
return n;
}
}
上面无法编译,因为 n 不是不是 constexpr。
您当然可以使用一个简单的 if,它会在编译时进行评估:
// compiles
consteval int abs(int n) {
if (n < 0) {
return -n;
}
else {
return n;
}
}
constexpr int i = -9;
constexpr int num = abs(i);
这是一个术语问题:
是否有一个在编译时已知,但不是常量表达式的常用名称?
【问题讨论】:
-
我会选择
constinit。对于这种特殊情况,它可能不是官方术语,但从语义上讲,它几乎可以检查出来。
标签: terminology c++20 consteval