gpt4 book ai didi

c++ - 我怎样才能干净地验证并转换为非顺序的枚举?

转载 作者:太空宇宙 更新时间:2023-11-04 12:50:43 24 4
gpt4 key购买 nike

<分区>

考虑以下代码:

//Note that the enum is nonsequential. I don't have control of
//this enum so I cannot change it to be sequential
enum class Animal {
DOG = 0,
CAT = 1,
LLAMA = 20,
ALPACA = 21,
};

//This data is received as an int,
//but I want to know what Animal it refers to
int data_0 = 0;
int data_2 = 2;

我的应用程序将收到一些数据,我想知道它指的是哪个 Animal。

Animal foo = static_cast<Animal>(data_0); //Great, it's an Animal::DOG.
Animal bar = static_cast<Animal>(data_2); //Whoops! This will crash.

if (foo == Animal::DOG) { //This is an easy comparison
//do something
}

显然,我需要对传入的数据进行一些验证,否则我有崩溃的风险。

对我来说,解决方案似乎是在转换枚举时进行显式验证,但我对 C++ 的了解不够,无法知道一种干净的方法来执行此操作:

//This is not sufficient to validate the value
if (data_2 > Animal::DOG && data_2 < Animal::ALPACA) {
Animal bar = static_cast<Animal>(data_2); //Whoops! This will crash.
}

//This is sufficient to validate the value, but is very ugly
Animal bar;
if (data_2 == static_cast<int>(Animal::DOG) ||
data_2 == static_cast<int>(Animal::CAT) ||
data_2 == static_cast<int>(Animal::LLAMA) ||
data_2 == static_cast<int>(Animal::ALPACA)) {
bar = static_cast<Animal>(data_2); //This does not run because of the checking
}

//bar was not assigned, so it would be NULL or 0
if (bar == Animal::DOG) {
//oh no, we shouldn't be here!
}

必须有更好的方法来做到这一点,所以我觉得我错过了什么。我该如何设计才能将 int 转换为 Animal,但当转换失败时 Animal 不能最终成为无效值?

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