如何检查枚举值是否有效? [英] How to check if enum value is valid?

查看:128
本文介绍了如何检查枚举值是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从二进制文件中读取一个枚举值,并希望检查该值是否真的属于枚举值。我该怎么做?

I am reading an enum value from a binary file and would like to check if the value is really part of the enum values. How can I do it?

#include <iostream>

enum Abc
{
    A = 4,
    B = 8,
    C = 12
};

int main()
{
    int v1 = 4;
    Abc v2 = static_cast< Abc >( v1 );

    switch ( v2 )
    {
        case A:
            std::cout<<"A"<<std::endl;
            break;
        case B:
            std::cout<<"B"<<std::endl;
            break;
        case C:
            std::cout<<"C"<<std::endl;
            break;
        default :
            std::cout<<"no match found"<<std::endl;
    }
}

我必须使用开关运算符还是有更好的方法?

Do I have to use the switch operator or is there a better way?

编辑

我有枚举值设置,不幸的是我不能修改它们。更糟糕的是,它们不是连续的(它们的值为0,75,76,80,85,90,95,100等)。

I have enum values set and unfortunately I can not modify them. To make things worse, they are not continuous (their values goes 0, 75,76,80,85,90,95,100, etc.)

推荐答案

枚举值在C ++中有效,如果它在下面的标准规则定义的范围[A,B]中。因此,在枚举X {A = 1,B = 3} 的情况下, 2 的值被认为是有效的枚举值

enum value is valid in C++ if it falls in range [A, B], which is defined by the standard rule below. So in case of enum X { A = 1, B = 3 }, the value of 2 is considered a valid enum value.

考虑标准的7.2 / 6:

Consider 7.2/6 of standard:


对于枚举,其中emin是最小的枚举器和emax是最大的,枚举的值是在bmax到bmax的范围内的底层类型的值,其中bmin和bmax分别是可以存储的最小位字段的最小和最大值emin和emax可以定义一个枚举,它的值不是由任何枚举器定义的。
For an enumeration where emin is the smallest enumerator and emax is the largest, the values of the enumeration are the values of the underlying type in the range bmin to bmax, where bmin and bmax are, respectively, the smallest and largest values of the smallest bit-field that can store emin and emax. It is possible to define an enumeration that has values not defined by any of its enumerators.

C ++没有回溯。一种方法是在数组中列出枚举值,并编写一个可以进行转换的包装器,并可能在失败时抛出异常。

There is no retrospection in C++. One approach to take is to list enum values in an array additionally and write a wrapper that would do conversion and possibly throw an exception on failure.

请参阅类似的问题有关如何将int转换为枚举以获取更多详细信息。

See Similar Question about how to cast int to enum for further details.

这篇关于如何检查枚举值是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆