[英]How to obtain a constant expression when std::is_constant_evaluated?
Let's start with the example ( godbolt ):让我们从示例( godbolt )开始:
constexpr int len(int v) {
if (std::is_constant_evaluated()) {
// static_assert(v > 0); // ERR: 'v' is not a constant expression
return v;
} else {
return 0;
}
}
using A = std::array<int, len(3)>;
The problem is, that the static_assert
won't compile (gcc / clang latest 10.x releases).问题是,
static_assert
无法编译(gcc / clang 最新的 10.x 版本)。 Apparently, v
isn't realized to be constexpr
when std::is_constant_evaluated
returns true
.显然,当
std::is_constant_evaluated
返回true
时, v
没有意识到是constexpr
。 But clearly, by the use of len
, it actually is.但显然,通过使用
len
,它实际上是。
Question : Is it possible to use a variable as constexpr
if and only if std::is_constant_evaluated
?问题:当且仅当
std::is_constant_evaluated
时,是否可以将变量用作constexpr
? If so, how?如果是这样,怎么做?
Apparently,
v
isn't realized to beconstexpr
whenstd::is_constant_evaluated
returnstrue
.显然,当
std::is_constant_evaluated
返回true
时,v
没有意识到是constexpr
。 But clearly, by the use oflen
, it actually is.但显然,通过使用
len
,它实际上是。
No, it's actually not.不,实际上不是。
Function parameters are not constant expressions. Function 参数不是常量表达式。 It doesn't matter if you're in the middle of constant evaluation or not.
无论您是否正在进行持续评估,都没有关系。 You cannot use
v
as a constant expression in any context.您不能在任何上下文中将
v
用作常量表达式。 static_assert
requires a constant expression - this is why you cannot use v
. static_assert
需要一个常量表达式——这就是你不能使用v
的原因。
Question: Is it possible to use a variable as constexpr if and only if
std::is_constant_evaluated
?问题:当且仅当
std::is_constant_evaluated
时,是否可以将变量用作 constexpr ? If so, how?如果是这样,怎么做?
No, it is not.不它不是。 Because in order to use a variable as a constant expression, well, that's a template.
因为为了将变量用作常量表达式,嗯,那是一个模板。 And
is_constant_evaluated
can't conditionally make your function into a function template, that's just not how the compilation process can work.并且
is_constant_evaluated
不能有条件地将您的 function 变成 function 模板,这不是编译过程可以工作的方式。 See P0992 .见P0992 。
Not possible, but also unnecessary.不可能,但也没有必要。
Instead of using a static_assert
, you can throw
something.您可以
throw
一些东西,而不是使用static_assert
。 Since you're in a constexpr
context, it will give you a compile-time error.由于您处于
constexpr
上下文中,因此它会给您一个编译时错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.