在 C++ 中使用枚举进行面向整数位的操作可靠/安全?
考虑以下(简化的)代码:
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;
}
这是可靠、安全和/或良好的做法吗?或者除了使用 const ints 而不是 enum 之外,还有更好的方法来实现我想要做的事情吗?我真的更喜欢枚举,但代码可靠性比可读性更重要。
Consider the following (simplified) code:
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;
}
Is this reliable, safe and/or good practice? Or is there a better way of achieving what i want to do apart from using const ints instead of enum? I would really prefer enums, but code reliability is more important than readability.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我看不出这个设计有什么不好的地方。
但是,请记住,
enum
类型可以保存未指定的值。根据谁使用您的函数,您可能需要首先检查 tsm 的值是否是有效的枚举值。由于枚举是整数值,因此可以执行以下操作:
但是,这样做很丑陋,您可能会认为这样做会导致未定义的行为。
I can't see anything bad in that design.
However, keep in mind that
enum
types can hold unspecified values. Depending on who uses your functions, you might want to check first that the value oftsm
is a valid enumeration value.Since
enums
are integer values, one could do something like:However, doing this is ugly and you might just consider that doing so results in undefined behavior.
没有问题。您甚至可以使用 eTestMode 变量(并为该类型定义位操作),因为在这种情况下它保证保存所有可能的值。
There is no problem. You can even use an variable of eTestMode (and defines bit manipulation for that type) as it is guaranteed to hold all possible values in that case.
参见
C 中枚举的大小是多少?
对于某些编译器(例如 VC++),可以使用此非标准宽度说明符:
See also
What is the size of an enum in C?
For some compilers (e.g. VC++) this non-standard width specifier can be used:
使用枚举来表示位模式、掩码和标志并不总是一个好主意,因为枚举通常会提升为有符号整数类型,而对于基于位的操作无符号类型几乎总是更可取。
Using enums for representing bit patterns, masks and flags is not always a good idea because enums generally promote to signed integer type, while for bit-based operation unsigned types are almost always preferable.