简体   繁体   English

检查作用域枚举是否包含值

[英]Checking whether a scoped enum contains a value

I haven't seen a clear answer to this question about enums.我还没有看到关于枚举的这个问题的明确答案。 Lets say I have an enum:可以说我有一个枚举:

enum class TileType
{
    WALL= 'W',
    PASSAGE= 'P',
    MONSTER = 'M',
    CRYSTAL= 'C',
};

and I want to typecast and make a new enum with a char Lets say the input char is undefined it the enum:我想使用 char 进行类型转换并创建一个新的枚举让我们说输入 char 在枚举中是未定义的:

char id = 'A';

Now when I typecast it there is an undefined behaviour:现在,当我对它进行类型转换时,会出现未定义的行为:

TileType type = static_cast<TileType>(id);

Thats why I want to check if the id is a valid value for an enum这就是为什么我想检查 id 是否是枚举的有效值

//check if enum contains id
bool checkID(char id){...}

Now I have a couple ideas to do it but they seem like over kill to me.现在我有几个想法可以做到,但它们对我来说似乎太过分了。 I also couldn't find a way to iterate over the enum class to make the check easy but I don't think that's possible.我也找不到一种方法来遍历枚举 class 以简化检查,但我认为这是不可能的。

Is there a way to easily check if the enum contains the id so that I can decide if I can typecast or not?有没有一种方法可以轻松检查枚举是否包含 id,以便我可以决定是否可以进行类型转换? Or am I supposed to do like a switch statement and check for every single case?还是我应该像 switch 语句一样检查每个案例?

Or am I supposed to do like a switch statement and check for every single case?还是我应该像 switch 语句一样检查每个案例?

This is probably a decent solution.这可能是一个不错的解决方案。 Like this:像这样:

switch(id) {
    case char(TileType::WALL):
    case char(TileType::PASSAGE):
    case char(TileType::MONSTER):
    case char(TileType::CRYSTAL):
        return true;
    default:
        return false;
}

Another alternative is to store all valid values in a data structure such as an array:另一种方法是将所有有效值存储在数据结构中,例如数组:

constexpr std::array valid {
    char(TileType::WALL),
    char(TileType::PASSAGE),
    char(TileType::MONSTER),
    char(TileType::CRYSTAL),
};

With such data structure, you can check validity like this:使用这样的数据结构,您可以像这样检查有效性:

return std::ranges::find(valid, id) != valid.end();

Compilers tend to be better at optimising the switch.编译器往往更擅长优化开关。


In either case, it may be useful to use meta-programming to generate the switch / the array.在任何一种情况下,使用元编程来生成开关/数组都可能很有用。

There is no standard way to do this.没有标准的方法可以做到这一点。 One way is to use a third-party library like magic_enum , which may still have limitations on the enum's range.一种方法是使用像magic_enum这样的第三方库,它可能仍然对枚举的范围有限制。

enum class TileType
{
    WALL= 'W',
    PASSAGE= 'P',
    MONSTER = 'M',
    CRYSTAL= 'C',
};

bool contains = magic_enum::enum_contains<TileType>('A');

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM