gpt4 book ai didi

c++ - 在 if 语句中禁用枚举赋值 g++

转载 作者:行者123 更新时间:2023-11-28 02:16:17 24 4
gpt4 key购买 nike

我想将 if 语句中的赋值视为错误:

#include <cstdio>

enum some {
a,
b
};

void foo(some e) {
if (e = a) {
puts("yes");
} else {
puts("no");
}
}

int main() {
foo(a);
return 0;
}

这似乎是一件理智的事情,除了我也想拥有这样的东西:

boost::optional<int> optionalValue;
if (const auto& value = optionalValue) {

}

-Wall给我enum.cpp:9: warning: suggest parentheses around assignment used as truth value , 但我想要比 -Wall 更具体的东西

最佳答案

您可以将e 声明为const。那么赋值就会出错。

或者,您可以使用 -Werror 告诉 g++ 将警告视为错误。然后,加上适当的警告设置,if 表达式中的任何赋值都将是错误的。您可以使用 -Wparentheses 仅启用此类警告。但是,请注意,有时这不是错误,而是故意的。这就是为什么 g++ 建议使用括号来消除意外赋值的歧义。

关于c++ - 在 if 语句中禁用枚举赋值 g++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33934744/

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