[英]Why static_assert error: "expression must have a constant value" even if I do pass constants?
[英]How can I fix this error “the value of 'x1' is not usable in a constant expression” ? static_assert
给出以下代码( 仅用于示例 ):
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;
否则,编译器如何知道(完全通用性和一致性) x1
和x2
是编译时可评估的常量表达式?
如果x1
和x2
需要是int
类型,那么你需要使用运行时断言,例如assert
:
assert(x1 != x2)
但请注意,如果定义了NDEBUG
则不会计算传递给assert
的表达式。 如果表达式具有副作用,那么可能会导致不同构建配置出现问题。
您必须使用运行时断言,如:
#include <cassert>
// ...
int x1 = 4;
int x2 = 5;
assert(x1 != x2);
注意:使用assert的运行时断言仅在调试模式下编译时适用,在发布模式下进行编译时会将其删除。 因此,它们不会减慢应用程序的速度。 他们是零成本 ,所以你可以(而且按理说应该 )使用它们自由地检查边界条件和一般的正确性。
一个重要的考虑因素(道具@Bathsheba)是这些断言 不应该调用的副作用 ,因为随后的调试版本和发行版本之间的行为会有所不同。
例如。
// in the release version x2 will NOT be incremented!!!
assert(x1 != x2++); // BAD!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.