键入安全枚举位标志 [英] Type safe enum bit flags

查看:202
本文介绍了键入安全枚举位标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在考虑使用一组位标志。这些标志(很好地)被定义为枚举的一部分,但是我明白当你 OR 枚举 OR 操作的返回类型具有类型 int

I'm looking to use a set of bit flags for my current issue. These flags are (nicely) defined as part of an enum, however I understand that when you OR two values from an enum the return type of the OR operation has type int.

我正在寻找的是一个解决方案,它将允许位掩码的用户保持类型安全,因此我已经为 operator |

What I'm currently looking for is a solution which will allow the users of the bit mask to remain type safe, as such I have created the following overload for operator |

enum ENUM
{
    ONE     = 0x01,
    TWO     = 0x02,
    THREE   = 0x04,
    FOUR    = 0x08,
    FIVE    = 0x10,
    SIX     = 0x20
};

ENUM operator | ( ENUM lhs, ENUM rhs )
{
    // Cast to int first otherwise we'll just end up recursing
    return static_cast< ENUM >( static_cast< int >( lhs ) | static_cast< int >( rhs ) );
}

void enumTest( ENUM v )
{
}

int main( int argc, char **argv )
{
    // Valid calls to enumTest
    enumTest( ONE | TWO | FIVE );
    enumTest( TWO | THREE | FOUR | FIVE );
    enumTest( ONE | TWO | THREE | FOUR | FIVE | SIX );

    return 0;
}

这个重载真的提供了类型安全吗?是否在枚举中引用未定义的行为的 int ?有没有注意事项?

Does this overload really provide type safety? Does casting an int containing values not defined in the enum cause undefined behaviour? Are there any caveats to be aware of?

推荐答案


这个重载是否真的提供了类型安全? / p>

Does this overload really provide type safety?

在这种情况下,是的。枚举的有效范围至少达到(但不一定包括)最大命名枚举器之后的两个最大权力,以便允许将其用于这样的位掩码。所以对这两个值的任何按位操作都会给出一个这种类型可以表示的值。

In this case, yes. The valid range of values for the enumeration goes at least up to (but not necessarily including) the next largest power of two after the largest named enumerator, in order to allow it to be used for bitmasks like this. So any bitwise operation on two values will give a value representable by this type.


转换一个包含未在枚举原因中定义的值的int未定义行为?

Does casting an int containing values not defined in the enum cause undefined behaviour?

不,只要值可以通过枚举表示,他们在这里。

No, as long as the values are representable by the enumeration, which they are here.


有没有需要注意的注意事项?

Are there any caveats to be aware of?

如果你在做操作例如算术,可以将值超出范围,那么您将获得一个实现定义的结果,但不会得到未定义的行为。

If you were doing operations such as arithmetic, which could take the value out of range, then you'd get an implementation-defined result, but not undefined behavoiur.

这篇关于键入安全枚举位标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆