Enumeration type in C ++
C ++ 11 provides a safer Enumeration type and cannot be used directly as an integer. But what if we want to use it as an integer?
For example
Enum class ElemType
{
CAP,
IND,
VS
};
In the past, when we used the enumeration type, we did not add the class keyword, which can be defined as follows,
Enum ElemTypeOld
{
CAP = 1,
IND,
VS = 3
};
After defining an enumerated variable, you can directly compare it with an integer. However, there are some problems in this process, because the custom integer values may not be consecutive, and some are defined, and others are not defined.
When ElemTypeOld: IND is output, 2 is output. If the CAP value is changed to 2, the IND value is 3, which is the same as the VS value. (This is also the case when ElemType does the same. This is not the case if the type is safer .)
In ElemTypeOld, whether or not an integer is specified, it can be used as an integer. In ElemType, it can only be used as an enumeration type and cannot be mixed with an integer. C ++ also provides the method to convert it to an integer,
Static_cast <int> (ElemType: CAP)-> 0,
If an integer is specified in ElemType, the specified integer is obtained.
I originally wanted to convert the enumerated type into string output, but encountered the above problem when converting it into an integer. Next, go to the topic.
One way is to use the swicth statement,
String getElemTypeName (ElemType type)
{
Switch (type)
{
Case ElemType: CAP: return "CAP"; break;
Case ElemType: IND: return "IND"; break;
Case ElemType: VS: return "VS"; break;
Default: return "error"; break;
}
}
Another method is to define a constant string array,
Const char * names [] = {"CAP", "IND", ""};
String getElemTypeName (ElemType type)
{
Int idx = static_cast <int> (type );
Return names [idx];
}
There are other ways to use macro definition on the Internet. I think these two methods are enough.