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

问题描述

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

  #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:

在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:

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.

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

05-26 11:01
查看更多