如何修复此错误"the value of 'x1' is not usable in a constant expression"?static_assert

How can I fix this error "the value of 'x1' is not usable in a constant expression" ? static_assert

本文关键字:in constant expression assert static usable x1 错误 何修复 the value      更新时间:2023-10-16

给定以下代码(仅用于示例(:

int x1 = 4;
int x2 = 5;
static_assert(x1 != x2 ,"Error");

我收到以下错误:

"x1"的值在常量表达式中不可用

我该如何解决?


注意:我正在寻找一种在不以这种方式更改变量定义的情况下修复它的方法:

const int x1 = 4;
const int x2 = 5;

但是,我只想通过更改static_assert(..)行来修复它

好吧,正确的解决方法是

constexpr int x1 = 4;
constexpr int x2 = 5;

否则,编译器如何知道(完全通用和一致性(x1x2是编译时可评估的常量表达式?

如果需要int类型x1x2,则需要使用运行时断言,例如assert

assert(x1 != x2)

但请注意,如果定义了NDEBUG不会计算传递给assert的表达式。如果表达式有副作用,这可能会导致不同生成配置出现问题。

参考: https://en.cppreference.com/w/cpp/error/assert

您必须使用运行时断言,例如:

#include <cassert>
// ...
int x1 = 4;
int x2 = 5;
assert(x1 != x2);

注意:使用 assert 的运行时断言仅在调试模式下编译时适用,在发布模式下编译时会将其删除。因此,它们不会减慢应用程序的速度。它们是零成本的,因此您可以(并且应该(自由地使用它们来检查边界条件和一般正确性。

一个重要的考虑因素(props @Bathsheba(是这些断言不应调用副作用,因为这样调试版本和发布版本之间的行为就会不同。

例如。

// in the release version x2 will NOT be incremented!!!
assert(x1 != x2++); // BAD!!