我正在读取enum二进制文件中的值,并想检查该值是否真的是enum值的一部分.我该怎么做?
#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;
}
}
Run Code Online (Sandbox Code Playgroud)
我是否必须使用switch操作员或有更好的方法吗?
编辑
我设置了枚举值,不幸的是我无法修改它们.更糟糕的是,它们不是连续的(它们的值为0,75,76,80,85,90,95,100等)
我有一个枚举:
enum myenum{
typeA,
typeB,
typeC
} myenum_t;
Run Code Online (Sandbox Code Playgroud)
然后,使用enum参数调用函数:
int myfunction(myenum_t param1)
{
switch(param1)
{
case typeA:
case typeB:
case typeC:
//do the work
break;
default:
printf("Invalid parameter");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,随着myenum_t越来越多的价值观的增长,myfunction似乎并不那么优雅.
有没有更好的方法来检查枚举是否有效?