gpt4 book ai didi

c++ - 如何修复此错误 "the value of ' x 1' is not usable in a constant expression"?静态断言

转载 作者:太空狗 更新时间:2023-10-29 23:43:27 24 4
gpt4 key购买 nike

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

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

我收到以下错误:

the value of 'x1' is not usable in a constant expression

我该如何解决?


注意:我正在寻找一种方法来修复它而不用这种方式更改变量的定义:

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

但是,我只想通过更改 static_assert(..)

行来修复它

最佳答案

嗯,正确的解决方法是

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

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

如果x1x2 需要是int 类型,那么您需要使用运行时断言,例如assert:

assert(x1 != x2)

但是请注意,如果定义了 NDEBUG,传递给 assert 的表达式将求值。如果表达式有副作用,这可能会导致不同构建配置出现问题。

引用:https://en.cppreference.com/w/cpp/error/assert

关于c++ - 如何修复此错误 "the value of ' x 1' is not usable in a constant expression"?静态断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51101015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com