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

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

问题描述

我从二进制文件中读取一个枚举值,并想检查该值是否真的是枚举值。我该如何做?

  #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;
}
}

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



EDIT



我设置了枚举值,很遗憾,我无法修改它们。更糟糕的是,它们不是连续的(它们的值为0,75,76,80,85,90,95,100等)。

解决方案

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



考虑标准的7.2 / 6:


对于emin最小的枚举器和emax是最大的,枚举的值是在范围bmin到bmax中的基础类型的值,其中bmin和bmax分别是可以存储的最小位字段的最小和最大值emin和emax。可以定义具有未由任何其枚举器定义的值的枚举。

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



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

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?

EDIT

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.)

解决方案

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.

Consider 7.2/6 of standard:

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.

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.

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

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

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