如何修复此错误"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
给定以下代码(仅用于示例(:
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
是编译时可评估的常量表达式?
如果需要int
类型x1
和x2
,则需要使用运行时断言,例如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!!
相关文章:
- netcat command in c++
- Difference in displaying cv2 Mat
- C++ MFC Libraries in Travis CI
- 如何在OpenSSL中从configuration.h.in获取configuration.h
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 为什么static_assert错误:即使我传递常量"expression must have a constant value"?
- IN, OUT, INOUT Parameters
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 有人安装"IITB Simplecpp in mac"吗?
- 从 C 样式字符串中删除子字符串 "in place" 在C++代码中
- 如何修复"error: ‘_1’ was not declared in this scope"?
- Softmax Implementation in C++
- 将 out/in out 参数与 if/switch 的 init 语句一起使用
- IF-nesting in c++
- Gurobi GRBModel and GRBmodel in C++
- Tensorflow Hub in C++
- Centos7 g++ "to_string is not in a member of std"
- 如何修复此错误"the value of 'x1' is not usable in a constant expression"?static_assert
- boost::asio::d eadline_timer 导致"a function call cannot appear in a constant-expression"错误
- " a variable that can be easily mistaken for a constant variable but is in fact a non-constant varia