c++ - 在 C++ 中使用枚举进行面向整数位的操作是否可靠/安全?

标签 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;
}

这是可靠、安全和/或良好的做法吗?或者除了使用 const int 而不是枚举之外,是否有更好的方法来实现我想做的事情?我真的更喜欢枚举,但代码可靠性比可读性更重要。

最佳答案

我看不出那个设计有什么不好。

但是,请记住 enum 类型可以包含未指定的值。根据谁使用您的函数,您可能需要先检查 tsm 的值是否是有效的枚举值。

因为 enums 是整数值,所以可以这样做:

eTestMode tsm = static_cast<eTestMode>(17); // We consider here that 17 is not a valid value for your enumeration.

但是,这样做很丑陋,您可能只是认为这样做会导致未定义的行为。

关于c++ - 在 C++ 中使用枚举进行面向整数位的操作是否可靠/安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3148850/

相关文章:

C++ 枚举与 C# 一样的属性

c++ - 在类中映射命名空间枚举

有条件地设置或清除位

c++ - OS X 中的 "Clang: error: no input files"

c++ - std::vector 中的自定义分配器

c# - 如何将枚举传递给函数以及如何在 if 语句 c# 中评估枚举

c++ - GCC 位扫描向前查找下一个设置位?

c++ - 通过左移,可以将数字设置为零

C++: std::vector - "slice"一个 vector 是可能的吗?

c++ - 当 Visual Studio 未以管理员身份运行时(GLFW/glad 应用程序),KernelBase.dll 异常代码 0x0EEDFADE(但没有崩溃)