Pet*_*erK 4 c++ enums bit-manipulation reliability
考虑以下(简化)代码:
enum eTestMode
{
TM_BASIC = 1, // 1 << 0
TM_ADV_1 = 1 << 1,
TM_ADV_2 = 1 << 2
};
...
int m_iTestMode; // a "bit field"
bool isSet( eTestMode tsm )
{
return ( (m_iTestMode & tsm) == tsm );
}
void setTestMode( eTestMode tsm )
{
m_iTestMode |= tsm;
}
Run Code Online (Sandbox Code Playgroud)
这是可靠,安全和/或良好的做法吗?或者除了使用const int而不是enum之外,还有更好的方法来实现我想做的事情吗?我更喜欢枚举,但代码可靠性比可读性更重要.
我在这个设计中看不出任何坏事.
但是,请记住,enum
类型可以包含未指定的值.根据谁使用您的函数,您可能希望首先检查值tsm
是否是有效的枚举值.
由于enums
是整数值,可以执行以下操作:
eTestMode tsm = static_cast<eTestMode>(17); // We consider here that 17 is not a valid value for your enumeration.
Run Code Online (Sandbox Code Playgroud)
但是,这样做很难看,您可能只是认为这样做会导致未定义的行为.