225

enums 视为标志在 C# 中通过[Flags],但是在 C++ 中执行此操作的最佳方法是什么?

例如,我想写:

enum AnimalFlags
{
    HasClaws = 1,
    CanFly =2,
    EatsFish = 4,
    Endangered = 8
};

seahawk.flags = CanFly | EatsFish | Endangered;

int但是,我收到有关/的编译器错误enum转换有没有比直截了当的铸造更好的方式来表达这一点?最好,我不想依赖来自 3rd 方库(如 boost 或 Qt)的构造。

编辑:如答案所示,我可以通过声明seahawk.flags为来避免编译器错误int。但是,我想有一些机制来强制类型安全,所以有人不能写seahawk.flags = HasMaximizeButton.

4

25 回答 25

289

“正确”的方法是为枚举定义位运算符,如:

enum AnimalFlags
{
    HasClaws   = 1,
    CanFly     = 2,
    EatsFish   = 4,
    Endangered = 8
};

inline AnimalFlags operator|(AnimalFlags a, AnimalFlags b)
{
    return static_cast<AnimalFlags>(static_cast<int>(a) | static_cast<int>(b));
}

等等其余的位运算符。如果枚举范围超出 int 范围,则根据需要进行修改。

于 2009-09-19T12:37:59.093 回答
147

注意(也有点离题):另一种制作唯一标志的方法可以使用位移来完成。我,我自己,发现这更容易阅读。

enum Flags
{
    A = 1 << 0, // binary 0001
    B = 1 << 1, // binary 0010
    C = 1 << 2, // binary 0100
    D = 1 << 3  // binary 1000
};

它最多可以保存一个 int 值,也就是说,大多数情况下,32 个标志清楚地反映在移位量中。

于 2012-04-06T09:09:40.227 回答
63

请注意,如果您在 Windows 环境中工作,DEFINE_ENUM_FLAG_OPERATORSwinnt.h 中定义了一个宏来为您完成这项工作。所以在这种情况下,你可以这样做:

enum AnimalFlags
{
    HasClaws = 1,
    CanFly =2,
    EatsFish = 4,
    Endangered = 8
};
DEFINE_ENUM_FLAG_OPERATORS(AnimalFlags)

seahawk.flags = CanFly | EatsFish | Endangered;
于 2013-10-25T14:16:27.803 回答
61

对于像我这样的懒人,这里是复制粘贴的模板解决方案:

template<class T> inline T operator~ (T a) { return (T)~(int)a; }
template<class T> inline T operator| (T a, T b) { return (T)((int)a | (int)b); }
template<class T> inline T operator& (T a, T b) { return (T)((int)a & (int)b); }
template<class T> inline T operator^ (T a, T b) { return (T)((int)a ^ (int)b); }
template<class T> inline T& operator|= (T& a, T b) { return (T&)((int&)a |= (int)b); }
template<class T> inline T& operator&= (T& a, T b) { return (T&)((int&)a &= (int)b); }
template<class T> inline T& operator^= (T& a, T b) { return (T&)((int&)a ^= (int)b); }
于 2014-04-18T10:51:06.877 回答
48

seahawk.flags 变量是什么类型的?

在标准 C++ 中,枚举不是类型安全的。它们实际上是整数。

AnimalFlags 不应该是变量的类型。您的变量应该是 int 并且错误会消失。

不需要像其他人建议的那样放置十六进制值。没什么区别。

默认情况下,枚举值是 int 类型。所以你当然可以按位或组合它们并将它们放在一起并将结果存储在一个 int 中。

enum 类型是 int 的受限子集,其值是其枚举值之一。因此,当您在该范围之外创建一些新值时,如果不强制转换为枚举类型的变量,就无法分配它。

如果您愿意,也可以更改枚举值类型,但这个问题没有意义。

编辑:张贴者说他们关心类型安全,他们不想要 int 类型中不应该存在的值。

但是,将 AnimalFlags 范围之外的值放入 AnimalFlags 类型的变量中是类型不安全的。

尽管在 int 类型中,有一种安全的方法来检查超出范围的值......

int iFlags = HasClaws | CanFly;
//InvalidAnimalFlagMaxValue-1 gives you a value of all the bits 
// smaller than itself set to 1
//This check makes sure that no other bits are set.
assert(iFlags & ~(InvalidAnimalFlagMaxValue-1) == 0);

enum AnimalFlags {
    HasClaws = 1,
    CanFly =2,
    EatsFish = 4,
    Endangered = 8,

    // put new enum values above here
    InvalidAnimalFlagMaxValue = 16
};

上述内容并不能阻止您从具有值 1、2、4 或 8 的不同枚举中放置无效标志。

如果您想要绝对类型安全,那么您可以简单地创建一个 std::set 并将每个标志存储在其中。它不节省空间,但它是类型安全的,并为您提供与 bitflag int 相同的功能。

C++0x 注意:强类型枚举

在 C++0x 中,您终于可以拥有类型安全的枚举值......

enum class AnimalFlags {
    CanFly = 2,
    HasClaws = 4
};

if(CanFly == 2) { }//Compiling error
于 2009-09-19T11:52:07.770 回答
33

我发现eidolon目前接受的答案太危险了。编译器的优化器可能会对枚举中的可能值做出假设,并且您可能会得到带有无效值的垃圾。通常没有人想在标志枚举中定义所有可能的排列。

正如下面的 Brian R. Bondy 所说,如果您使用的是 C++11(每个人都应该这样做,那就太好了),您现在可以通过以下方式更轻松地做到这一点enum class

enum class ObjectType : uint32_t
{
    ANIMAL = (1 << 0),
    VEGETABLE = (1 << 1),
    MINERAL = (1 << 2)
};


constexpr enum ObjectType operator |( const enum ObjectType selfValue, const enum ObjectType inValue )
{
    return (enum ObjectType)(uint32_t(selfValue) | uint32_t(inValue));
}

// ... add more operators here. 

这通过指定枚举的类型来确保稳定的大小和值范围,通过使用禁止将枚举自动向下转换为整数等enum class,并用于constexpr确保运算符的代码被内联,因此与常规数字一样快。

对于那些坚持使用 11 之前的 C++ 方言的人

如果我遇到了不支持 C++11 的编译器,我会在一个类中包装一个 int 类型,然后只允许使用位运算符和该枚举中的类型来设置其值:

template<class ENUM,class UNDERLYING=typename std::underlying_type<ENUM>::type>
class SafeEnum
{
public:
    SafeEnum() : mFlags(0) {}
    SafeEnum( ENUM singleFlag ) : mFlags(singleFlag) {}
    SafeEnum( const SafeEnum& original ) : mFlags(original.mFlags) {}

    SafeEnum&   operator |=( ENUM addValue )    { mFlags |= addValue; return *this; }
    SafeEnum    operator |( ENUM addValue )     { SafeEnum  result(*this); result |= addValue; return result; }
    SafeEnum&   operator &=( ENUM maskValue )   { mFlags &= maskValue; return *this; }
    SafeEnum    operator &( ENUM maskValue )    { SafeEnum  result(*this); result &= maskValue; return result; }
    SafeEnum    operator ~()    { SafeEnum  result(*this); result.mFlags = ~result.mFlags; return result; }
    explicit operator bool()                    { return mFlags != 0; }

protected:
    UNDERLYING  mFlags;
};

您可以像常规枚举 + typedef 一样定义它:

enum TFlags_
{
    EFlagsNone  = 0,
    EFlagOne    = (1 << 0),
    EFlagTwo    = (1 << 1),
    EFlagThree  = (1 << 2),
    EFlagFour   = (1 << 3)
};

typedef SafeEnum<enum TFlags_>  TFlags;

用法也类似:

TFlags      myFlags;

myFlags |= EFlagTwo;
myFlags |= EFlagThree;

if( myFlags & EFlagTwo )
    std::cout << "flag 2 is set" << std::endl;
if( (myFlags & EFlagFour) == EFlagsNone )
    std::cout << "flag 4 is not set" << std::endl;

您还可以enum foo : type使用第二个模板参数,即typedef SafeEnum<enum TFlags_,uint8_t> TFlags;.

operator bool用 C++11 的关键字标记了覆盖,explicit以防止它导致 int 转换,因为这可能导致标志集在写出它们时最终折叠为 0 或 1。如果您不能使用 C++11,请忽略该重载并将示例用法中的第一个条件重写为(myFlags & EFlagTwo) == EFlagTwo.

于 2015-11-28T13:18:34.273 回答
18

使用标准库类bitset最简单的方法如下所示

要以类型安全的方式模拟 C# 功能,您必须围绕位集编写模板包装器,将 int 参数替换为作为模板类型参数提供的枚举。就像是:

    template <class T, int N>
class FlagSet
{

    bitset<N> bits;

    FlagSet(T enumVal)
    {
        bits.set(enumVal);
    }

    // etc.
};

enum MyFlags
{
    FLAG_ONE,
    FLAG_TWO
};

FlagSet<MyFlags, 2> myFlag;
于 2009-09-19T12:40:44.693 回答
14

在我看来,到目前为止,没有一个答案是理想的。理想情况下,我希望解决方案:

  1. 支持传统意义上的, ==, !=, =, &,&=|运算符(即)|=~a & b
  2. 类型安全,即不允许分配非枚举值,例如文字或整数类型(枚举值的按位组合除外)或允许将枚举变量分配给整数类型
  3. 允许表达式,例如if (a & b)...
  4. 不需要邪恶的宏,实现特定的功能或其他黑客

到目前为止,大多数解决方案都落在第 2 点或第 3 点上。在我看来,WebDancer 是关闭的,但在第 3 点失败,需要为每个枚举重复。

我提出的解决方案是 WebDancer 的通用版本,它也解决了第 3 点:

#include <cstdint>
#include <type_traits>

template<typename T = typename std::enable_if<std::is_enum<T>::value, T>::type>
class auto_bool
{
    T val_;
public:
    constexpr auto_bool(T val) : val_(val) {}
    constexpr operator T() const { return val_; }
    constexpr explicit operator bool() const
    {
        return static_cast<std::underlying_type_t<T>>(val_) != 0;
    }
};

template <typename T = typename std::enable_if<std::is_enum<T>::value, T>::type>
constexpr auto_bool<T> operator&(T lhs, T rhs)
{
    return static_cast<T>(
        static_cast<typename std::underlying_type<T>::type>(lhs) &
        static_cast<typename std::underlying_type<T>::type>(rhs));
}

template <typename T = typename std::enable_if<std::is_enum<T>::value, T>::type>
constexpr T operator|(T lhs, T rhs)
{
    return static_cast<T>(
        static_cast<typename std::underlying_type<T>::type>(lhs) |
        static_cast<typename std::underlying_type<T>::type>(rhs));
}

enum class AnimalFlags : uint8_t 
{
    HasClaws = 1,
    CanFly = 2,
    EatsFish = 4,
    Endangered = 8
};

enum class PlantFlags : uint8_t
{
    HasLeaves = 1,
    HasFlowers = 2,
    HasFruit = 4,
    HasThorns = 8
};

int main()
{
    AnimalFlags seahawk = AnimalFlags::CanFly;        // Compiles, as expected
    AnimalFlags lion = AnimalFlags::HasClaws;         // Compiles, as expected
    PlantFlags rose = PlantFlags::HasFlowers;         // Compiles, as expected
//  rose = 1;                                         // Won't compile, as expected
    if (seahawk != lion) {}                           // Compiles, as expected
//  if (seahawk == rose) {}                           // Won't compile, as expected
//  seahawk = PlantFlags::HasThorns;                  // Won't compile, as expected
    seahawk = seahawk | AnimalFlags::EatsFish;        // Compiles, as expected
    lion = AnimalFlags::HasClaws |                    // Compiles, as expected
           AnimalFlags::Endangered;
//  int eagle = AnimalFlags::CanFly |                 // Won't compile, as expected
//              AnimalFlags::HasClaws;
//  int has_claws = seahawk & AnimalFlags::CanFly;    // Won't compile, as expected
    if (seahawk & AnimalFlags::CanFly) {}             // Compiles, as expected
    seahawk = seahawk & AnimalFlags::CanFly;          // Compiles, as expected

    return 0;
}

这会创建必要运算符的重载,但使用 SFINAE 将它们限制为枚举类型。请注意,为简洁起见,我没有定义所有运算符,但唯一不同的是&. 运算符当前是全局的(即适用于所有枚举类型),但这可以通过将重载放在命名空间中(我所做的)或添加额外的 SFINAE 条件(可能使用特定的底层类型或专门创建的类型别名)来减少)。这underlying_type_t是一个 C++14 功能,但它似乎得到了很好的支持,并且很容易通过简单的 C++11 模拟template<typename T> using underlying_type_t = underlying_type<T>::type;

于 2016-02-27T16:56:33.923 回答
12

C++ 标准明确讨论了这一点,请参阅“17.5.2.1.3 位掩码类型”部分:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf

鉴于此“模板”,您将获得:

enum AnimalFlags : unsigned int
{
    HasClaws = 1,
    CanFly = 2,
    EatsFish = 4,
    Endangered = 8
};

constexpr AnimalFlags operator|(AnimalFlags X, AnimalFlags Y) {
    return static_cast<AnimalFlags>(
        static_cast<unsigned int>(X) | static_cast<unsigned int>(Y));
}

AnimalFlags& operator|=(AnimalFlags& X, AnimalFlags Y) {
    X = X | Y; return X;
}

其他运营商也类似。另请注意“constexpr”,如果您希望编译器能够在编译时执行运算符,则需要它。

如果您使用 C++/CLI 并希望能够分配给 ref 类的枚举成员,则需要使用跟踪引用:

AnimalFlags% operator|=(AnimalFlags% X, AnimalFlags Y) {
    X = X | Y; return X;
}

注意:此示例不完整,请参阅“17.5.2.1.3 位掩码类型”部分了解完整的运算符集。

于 2015-12-11T09:26:03.547 回答
8

只有语法糖。没有额外的元数据。

namespace UserRole // grupy
{ 
    constexpr uint8_t dea = 1;
    constexpr uint8_t red = 2;
    constexpr uint8_t stu = 4;
    constexpr uint8_t kie = 8;
    constexpr uint8_t adm = 16;
    constexpr uint8_t mas = 32;
}

整数类型的标志运算符才有效。

于 2018-02-22T09:34:03.830 回答
7

我使用以下宏:

#define ENUM_FLAG_OPERATORS(T)                                                                                                                                            \
    inline T operator~ (T a) { return static_cast<T>( ~static_cast<std::underlying_type<T>::type>(a) ); }                                                                       \
    inline T operator| (T a, T b) { return static_cast<T>( static_cast<std::underlying_type<T>::type>(a) | static_cast<std::underlying_type<T>::type>(b) ); }                   \
    inline T operator& (T a, T b) { return static_cast<T>( static_cast<std::underlying_type<T>::type>(a) & static_cast<std::underlying_type<T>::type>(b) ); }                   \
    inline T operator^ (T a, T b) { return static_cast<T>( static_cast<std::underlying_type<T>::type>(a) ^ static_cast<std::underlying_type<T>::type>(b) ); }                   \
    inline T& operator|= (T& a, T b) { return reinterpret_cast<T&>( reinterpret_cast<std::underlying_type<T>::type&>(a) |= static_cast<std::underlying_type<T>::type>(b) ); }   \
    inline T& operator&= (T& a, T b) { return reinterpret_cast<T&>( reinterpret_cast<std::underlying_type<T>::type&>(a) &= static_cast<std::underlying_type<T>::type>(b) ); }   \
    inline T& operator^= (T& a, T b) { return reinterpret_cast<T&>( reinterpret_cast<std::underlying_type<T>::type&>(a) ^= static_cast<std::underlying_type<T>::type>(b) ); }

它与上面提到的类似,但有一些改进:

  • 它是类型安全的(它不假设底层类型是 an int
  • 它不需要手动指定底层类型(与@LunarEclipse 的答案相反)

它确实需要包含 type_traits:

#include <type_traits>
于 2019-09-23T18:26:11.670 回答
6

我发现自己问了同样的问题,并提出了一个通用的基于 C++11 的解决方案,类似于 soru 的:

template <typename TENUM>
class FlagSet {

private:
    using TUNDER = typename std::underlying_type<TENUM>::type;
    std::bitset<std::numeric_limits<TUNDER>::max()> m_flags;

public:
    FlagSet() = default;

    template <typename... ARGS>
    FlagSet(TENUM f, ARGS... args) : FlagSet(args...)
    {   
        set(f);
    }   
    FlagSet& set(TENUM f)
    {   
        m_flags.set(static_cast<TUNDER>(f));
        return *this;
    }   
    bool test(TENUM f)
    {   
        return m_flags.test(static_cast<TUNDER>(f));
    }   
    FlagSet& operator|=(TENUM f)
    {   
        return set(f);
    }   
};

界面可以根据口味进行改进。然后它可以像这样使用:

FlagSet<Flags> flags{Flags::FLAG_A, Flags::FLAG_C};
flags |= Flags::FLAG_D;
于 2015-08-09T16:32:07.523 回答
5

如果您的编译器还不支持强类型枚举,您可以查看来自 c++ 源代码的以下文章:

从摘要:

本文提出了一种解决方案,即限制位操作以
仅允许安全和合法的操作,并将所有无效的位操作转变为编译时错误。最重要的是,位操作的语法保持不变,使用位的代码不需要修改,除非可能修复尚未检测到的错误。

于 2009-09-19T12:47:08.477 回答
4

如果您实际上没有使用单个枚举值(例如,您不需要关闭它们),并且您不担心维护二进制兼容性,那么这里是位掩码的一个选项:您不在乎你的比特住在哪里……你可能在哪里。此外,您最好不要太在意范围界定和访问控制。嗯,枚举对位域有一些不错的属性......想知道是否有人曾经尝试过:)

struct AnimalProperties
{
    bool HasClaws : 1;
    bool CanFly : 1;
    bool EatsFish : 1;
    bool Endangered : 1;
};

union AnimalDescription
{
    AnimalProperties Properties;
    int Flags;
};

void TestUnionFlags()
{
    AnimalDescription propertiesA;
    propertiesA.Properties.CanFly = true;

    AnimalDescription propertiesB = propertiesA;
    propertiesB.Properties.EatsFish = true;

    if( propertiesA.Flags == propertiesB.Flags )
    {
        cout << "Life is terrible :(";
    }
    else
    {
        cout << "Life is great!";
    }

    AnimalDescription propertiesC = propertiesA;
    if( propertiesA.Flags == propertiesC.Flags )
    {
        cout << "Life is great!";
    }
    else
    {
        cout << "Life is terrible :(";
    }
}

我们可以看到生活是美好的,我们有我们离散的价值观,我们对 & 和 | 有很好的理解。让我们心满意足,这仍然具有其位含义的上下文。一切都是一致且可预测的……对我来说……只要我继续在 Win10 x64 上使用带有 Update 3 的 Microsoft VC++ 编译器并且不要碰我的编译器标志 :)

即使一切都很好......我们现在对标志的含义有了一些背景,因为它在可怕的现实世界中与位域联合,你的程序可能负责的不仅仅是一个单独的任务,你可以仍然不小心(很容易)将不同联合的两个标志字段粉碎在一起(例如,AnimalProperties 和 ObjectProperties,因为它们都是整数),混合了你所有的位,这是一个可怕的错误追查......我怎么知道这篇文章中的很多人不经常使用位掩码,因为构建它们很容易,维护它们很困难。

class AnimalDefinition {
public:
    static AnimalDefinition *GetAnimalDefinition( AnimalFlags flags );   //A little too obvious for my taste... NEXT!
    static AnimalDefinition *GetAnimalDefinition( AnimalProperties properties );   //Oh I see how to use this! BORING, NEXT!
    static AnimalDefinition *GetAnimalDefinition( int flags ); //hmm, wish I could see how to construct a valid "flags" int without CrossFingers+Ctrl+Shift+F("Animal*"). Maybe just hard-code 16 or something?

    AnimalFlags animalFlags;  //Well this is *way* too hard to break unintentionally, screw this!
    int flags; //PERFECT! Nothing will ever go wrong here... 
    //wait, what values are used for this particular flags field? Is this AnimalFlags or ObjectFlags? Or is it RuntimePlatformFlags? Does it matter? Where's the documentation? 
    //Well luckily anyone in the code base and get confused and destroy the whole program! At least I don't need to static_cast anymore, phew!

    private:
    AnimalDescription m_description; //Oh I know what this is. All of the mystery and excitement of life has been stolen away :(
}

那么你将你的联合声明设为私有以防止直接访问“标志”,并且必须添加 getter/setter 和运算符重载,然后为所有这些创建一个宏,你基本上就回到了你尝试的地方使用枚举执行此操作。

不幸的是,如果您希望您的代码可移植,我认为没有任何方法可以 A)保证位布局或 B)在编译时确定位布局(因此您可以跟踪它并至少纠正跨版本/平台等) 具有位字段的结构中的偏移量

在运行时,您可以通过设置字段和对标志进行异或运算来查看哪些位确实发生了变化,这对我来说听起来很糟糕,尽管具有 100% 一致、独立于平台且完全确定性的解决方案(即:枚举)对我来说听起来很糟糕。

TL;DR:不要听仇恨者的意见。C++ 不是英语。仅仅因为从 C 继承的缩写关键字的字面定义可能不适合您的用法,并不意味着当关键字的 CC++ 定义绝对包含您的用例时,您不应该使用它。您还可以使用结构来为结构以外的事物建模,并为学校和社会种姓以外的事物建模。您可以将 float 用于接地的值。您可以将 char 用于既不是未燃烧也不是小说、戏剧或电影中的人物的变量。在语言规范之前去字典确定关键字含义的任何程序员都是......好吧,我会在那里保持沉默。

如果你确实希望你的代码以口语为模型,你最好用 Objective-C 编写,顺便提一下,它也大量使用枚举作为位域。

于 2016-08-06T01:34:32.297 回答
4

我想详细说明Uliwitness 的答案,修复他的 C++98 代码并使用Safe Bool idiom ,因为C++11 以下的 C++ 版本中缺少std::underlying_type<>模板和关键字。explicit

我还对其进行了修改,以便枚举值可以是连续的而无需任何显式分配,因此您可以拥有

enum AnimalFlags_
{
    HasClaws,
    CanFly,
    EatsFish,
    Endangered
};
typedef FlagsEnum<AnimalFlags_> AnimalFlags;

seahawk.flags = AnimalFlags() | CanFly | EatsFish | Endangered;

然后,您可以使用

seahawk.flags.value();

这是代码。

template <typename EnumType, typename Underlying = int>
class FlagsEnum
{
    typedef Underlying FlagsEnum::* RestrictedBool;

public:
    FlagsEnum() : m_flags(Underlying()) {}

    FlagsEnum(EnumType singleFlag):
        m_flags(1 << singleFlag)
    {}

    FlagsEnum(const FlagsEnum& original):
        m_flags(original.m_flags)
    {}

    FlagsEnum& operator |=(const FlagsEnum& f) {
        m_flags |= f.m_flags;
        return *this;
    }

    FlagsEnum& operator &=(const FlagsEnum& f) {
        m_flags &= f.m_flags;
        return *this;
    }

    friend FlagsEnum operator |(const FlagsEnum& f1, const FlagsEnum& f2) {
        return FlagsEnum(f1) |= f2;
    }

    friend FlagsEnum operator &(const FlagsEnum& f1, const FlagsEnum& f2) {
        return FlagsEnum(f1) &= f2;
    }

    FlagsEnum operator ~() const {
        FlagsEnum result(*this);
        result.m_flags = ~result.m_flags;
        return result;
    }

    operator RestrictedBool() const {
        return m_flags ? &FlagsEnum::m_flags : 0;
    }

    Underlying value() const {
        return m_flags;
    }

protected:
    Underlying  m_flags;
};
于 2017-04-04T16:46:15.847 回答
4

目前没有对枚举标志的语言支持,如果 Meta 类成为 c++ 标准的一部分,它可能会固有地添加此功能。

我的解决方案是创建仅枚举实例化模板函数,使用其基础类型为枚举类添加类型安全按位运算的支持:

文件:EnumClassBitwise.h

#pragma once
#ifndef _ENUM_CLASS_BITWISE_H_
#define _ENUM_CLASS_BITWISE_H_

#include <type_traits>

//unary ~operator    
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum& operator~ (Enum& val)
{
    val = static_cast<Enum>(~static_cast<std::underlying_type_t<Enum>>(val));
    return val;
}

// & operator
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum operator& (Enum lhs, Enum rhs)
{
    return static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) & static_cast<std::underlying_type_t<Enum>>(rhs));
}

// &= operator
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum operator&= (Enum& lhs, Enum rhs)
{
    lhs = static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) & static_cast<std::underlying_type_t<Enum>>(rhs));
    return lhs;
}

//| operator

template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum operator| (Enum lhs, Enum rhs)
{
    return static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) | static_cast<std::underlying_type_t<Enum>>(rhs));
}
//|= operator

template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum& operator|= (Enum& lhs, Enum rhs)
{
    lhs = static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) | static_cast<std::underlying_type_t<Enum>>(rhs));
    return lhs;
}

#endif // _ENUM_CLASS_BITWISE_H_

为了方便和减少错误,您可能还需要为枚举和整数包装位标志操作:

文件:BitFlags.h

#pragma once
#ifndef _BIT_FLAGS_H_
#define _BIT_FLAGS_H_

#include "EnumClassBitwise.h"

 template<typename T>
 class BitFlags
 {
 public:

     constexpr inline BitFlags() = default;
     constexpr inline BitFlags(T value) { mValue = value; }
     constexpr inline BitFlags operator| (T rhs) const { return mValue | rhs; }
     constexpr inline BitFlags operator& (T rhs) const { return mValue & rhs; }
     constexpr inline BitFlags operator~ () const { return ~mValue; }
     constexpr inline operator T() const { return mValue; }
     constexpr inline BitFlags& operator|=(T rhs) { mValue |= rhs; return *this; }
     constexpr inline BitFlags& operator&=(T rhs) { mValue &= rhs; return *this; }
     constexpr inline bool test(T rhs) const { return (mValue & rhs) == rhs; }
     constexpr inline void set(T rhs) { mValue |= rhs; }
     constexpr inline void clear(T rhs) { mValue &= ~rhs; }

 private:
     T mValue;
 };
#endif //#define _BIT_FLAGS_H_

可能的用法:

#include <cstdint>
#include <BitFlags.h>
void main()
{
    enum class Options : uint32_t
    { 
          NoOption = 0 << 0
        , Option1  = 1 << 0
        , Option2  = 1 << 1
        , Option3  = 1 << 2
        , Option4  = 1 << 3
    };

    const uint32_t Option1 = 1 << 0;
    const uint32_t Option2 = 1 << 1;
    const uint32_t Option3 = 1 << 2;
    const uint32_t Option4 = 1 << 3;

   //Enum BitFlags
    BitFlags<Options> optionsEnum(Options::NoOption);
    optionsEnum.set(Options::Option1 | Options::Option3);

   //Standard integer BitFlags
    BitFlags<uint32_t> optionsUint32(0);
    optionsUint32.set(Option1 | Option3); 

    return 0;
}
于 2018-10-08T21:12:45.817 回答
3

@Xaqq 提供了一种非常好的类型安全方式,可以在这里通过flag_set类使用枚举标志。

我在GitHub 上发布了代码,用法如下:

#include "flag_set.hpp"

enum class AnimalFlags : uint8_t {
    HAS_CLAWS,
    CAN_FLY,
    EATS_FISH,
    ENDANGERED,
    _
};

int main()
{
    flag_set<AnimalFlags> seahawkFlags(AnimalFlags::HAS_CLAWS
                                       | AnimalFlags::EATS_FISH
                                       | AnimalFlags::ENDANGERED);

    if (seahawkFlags & AnimalFlags::ENDANGERED)
        cout << "Seahawk is endangered";
}
于 2019-10-04T21:51:41.933 回答
2

这是我的解决方案,不需要任何重载或强制转换:

namespace EFoobar
{
    enum
    {
        FB_A    = 0x1,
        FB_B    = 0x2,
        FB_C    = 0x4,
    };
    typedef long Flags;
}

void Foobar(EFoobar::Flags flags)
{
    if (flags & EFoobar::FB_A)
        // do sth
        ;
    if (flags & EFoobar::FB_B)
        // do sth
        ;
}

void ExampleUsage()
{
    Foobar(EFoobar::FB_A | EFoobar::FB_B);
    EFoobar::Flags otherflags = 0;
    otherflags|= EFoobar::FB_B;
    otherflags&= ~EFoobar::FB_B;
    Foobar(otherflags);
}

我认为没关系,因为无论如何我们都会识别(非强类型)枚举和整数。

就像(更长的)旁注一样,如果您

  • 想要使用强类型枚举和
  • 不需要大量摆弄你的旗帜
  • 性能不是问题

我会想出这个:

#include <set>

enum class EFoobarFlags
{
    FB_A = 1,
    FB_B,
    FB_C,
};

void Foobar(const std::set<EFoobarFlags>& flags)
{
    if (flags.find(EFoobarFlags::FB_A) != flags.end())
        // do sth
        ;
    if (flags.find(EFoobarFlags::FB_B) != flags.end())
        // do sth
        ;
}

void ExampleUsage()
{
    Foobar({EFoobarFlags::FB_A, EFoobarFlags::FB_B});
    std::set<EFoobarFlags> otherflags{};
    otherflags.insert(EFoobarFlags::FB_B);
    otherflags.erase(EFoobarFlags::FB_B);
    Foobar(otherflags);
}

使用 C++11 初始化列表和enum class.

于 2014-11-01T15:52:55.117 回答
2

您正在混淆对象和对象集合。具体来说,您将二进制标志与二进制标志集混淆了。一个适当的解决方案如下所示:

// These are individual flags
enum AnimalFlag // Flag, not Flags
{
    HasClaws = 0,
    CanFly,
    EatsFish,
    Endangered
};

class AnimalFlagSet
{
    int m_Flags;

  public:

    AnimalFlagSet() : m_Flags(0) { }

    void Set( AnimalFlag flag ) { m_Flags |= (1 << flag); }

    void Clear( AnimalFlag flag ) { m_Flags &= ~ (1 << flag); }

    bool Get( AnimalFlag flag ) const { return (m_Flags >> flag) & 1; }

};
于 2014-09-25T23:00:10.803 回答
2

另一个宏解决方案,但与现有答案不同,它不使用reinterpret_cast(或 C-cast)在Enum&and之间进行转换Int&,这在标准 C++ 中是被禁止的(参见这篇文章)。

#define MAKE_FLAGS_ENUM(TEnum, TUnder)                                                                                             \
TEnum  operator~  ( TEnum  a          ) { return static_cast<TEnum> (~static_cast<TUnder> (a)                           ); }  \
TEnum  operator|  ( TEnum  a, TEnum b ) { return static_cast<TEnum> ( static_cast<TUnder> (a) |  static_cast<TUnder>(b) ); }  \
TEnum  operator&  ( TEnum  a, TEnum b ) { return static_cast<TEnum> ( static_cast<TUnder> (a) &  static_cast<TUnder>(b) ); }  \
TEnum  operator^  ( TEnum  a, TEnum b ) { return static_cast<TEnum> ( static_cast<TUnder> (a) ^  static_cast<TUnder>(b) ); }  \
TEnum& operator|= ( TEnum& a, TEnum b ) { a = static_cast<TEnum>(static_cast<TUnder>(a) | static_cast<TUnder>(b) ); return a; }  \
TEnum& operator&= ( TEnum& a, TEnum b ) { a = static_cast<TEnum>(static_cast<TUnder>(a) & static_cast<TUnder>(b) ); return a; }  \
TEnum& operator^= ( TEnum& a, TEnum b ) { a = static_cast<TEnum>(static_cast<TUnder>(a) ^ static_cast<TUnder>(b) ); return a; }

失去reinterpret_cast意味着我们不能再依赖x |= y语法了,但是通过将它们扩展成它们的x = x | y形式,我们不再需要它了。

注意:您可以使用std::underlying_type来获取TUnder,为简洁起见,我没有包含它。

于 2020-07-22T09:43:44.913 回答
1

如上(Kai)或执行以下操作。真正的枚举是“枚举”,你想要做的是有一个集合,因此你应该真正使用 stl::set

enum AnimalFlags
{
    HasClaws = 1,
    CanFly =2,
    EatsFish = 4,
    Endangered = 8
};

int main(void)
{
    AnimalFlags seahawk;
    //seahawk= CanFly | EatsFish | Endangered;
    seahawk= static_cast<AnimalFlags>(CanFly | EatsFish | Endangered);
}
于 2009-09-19T11:54:22.883 回答
1

这是一个惰性 C++11 解决方案,它不会改变枚举的默认行为。它也适用于enum structandenum class和 is constexpr

#include <type_traits>

template<class T = void> struct enum_traits {};

template<> struct enum_traits<void> {
    struct _allow_bitops {
        static constexpr bool allow_bitops = true;
    };
    using allow_bitops = _allow_bitops;

    template<class T, class R = T>
    using t = typename std::enable_if<std::is_enum<T>::value and
        enum_traits<T>::allow_bitops, R>::type;

    template<class T>
    using u = typename std::underlying_type<T>::type;
};

template<class T>
constexpr enum_traits<>::t<T> operator~(T a) {
    return static_cast<T>(~static_cast<enum_traits<>::u<T>>(a));
}
template<class T>
constexpr enum_traits<>::t<T> operator|(T a, T b) {
    return static_cast<T>(
        static_cast<enum_traits<>::u<T>>(a) |
        static_cast<enum_traits<>::u<T>>(b));
}
template<class T>
constexpr enum_traits<>::t<T> operator&(T a, T b) {
    return static_cast<T>(
        static_cast<enum_traits<>::u<T>>(a) &
        static_cast<enum_traits<>::u<T>>(b));
}
template<class T>
constexpr enum_traits<>::t<T> operator^(T a, T b) {
    return static_cast<T>(
        static_cast<enum_traits<>::u<T>>(a) ^
        static_cast<enum_traits<>::u<T>>(b));
}
template<class T>
constexpr enum_traits<>::t<T, T&> operator|=(T& a, T b) {
    a = a | b;
    return a;
}
template<class T>
constexpr enum_traits<>::t<T, T&> operator&=(T& a, T b) {
    a = a & b;
    return a;
}
template<class T>
constexpr enum_traits<>::t<T, T&> operator^=(T& a, T b) {
    a = a ^ b;
    return a;
}

要为枚举启用按位运算符:

enum class my_enum {
    Flag1 = 1 << 0,
    Flag2 = 1 << 1,
    Flag3 = 1 << 2,
    // ...
};

// The magic happens here
template<> struct enum_traits<my_enum> :
    enum_traits<>::allow_bitops {};

constexpr my_enum foo = my_enum::Flag1 | my_enum::Flag2 | my_enum::Flag3;
于 2021-11-19T01:48:42.287 回答
1

也许就像 Objective-C 的 NS_OPTIONS 一样。

#define ENUM(T1, T2) \
enum class T1 : T2; \
inline T1 operator~ (T1 a) { return (T1)~(int)a; } \
inline T1 operator| (T1 a, T1 b) { return static_cast<T1>((static_cast<T2>(a) | static_cast<T2>(b))); } \
inline T1 operator& (T1 a, T1 b) { return static_cast<T1>((static_cast<T2>(a) & static_cast<T2>(b))); } \
inline T1 operator^ (T1 a, T1 b) { return static_cast<T1>((static_cast<T2>(a) ^ static_cast<T2>(b))); } \
inline T1& operator|= (T1& a, T1 b) { return reinterpret_cast<T1&>((reinterpret_cast<T2&>(a) |= static_cast<T2>(b))); } \
inline T1& operator&= (T1& a, T1 b) { return reinterpret_cast<T1&>((reinterpret_cast<T2&>(a) &= static_cast<T2>(b))); } \
inline T1& operator^= (T1& a, T1 b) { return reinterpret_cast<T1&>((reinterpret_cast<T2&>(a) ^= static_cast<T2>(b))); } \
enum class T1 : T2

ENUM(Options, short) {
    FIRST  = 1 << 0,
    SECOND = 1 << 1,
    THIRD  = 1 << 2,
    FOURTH = 1 << 3
};

auto options = Options::FIRST | Options::SECOND;
options |= Options::THIRD;
if ((options & Options::SECOND) == Options::SECOND)
    cout << "Contains second option." << endl;
if ((options & Options::THIRD) == Options::THIRD)
    cout << "Contains third option." << endl;
return 0;

// Output:
// Contains second option. 
// Contains third option.
于 2018-08-31T19:21:50.220 回答
1

基于此线程中的其他一些答案的可复制粘贴“邪恶”宏:

#include <type_traits>

/*
 * Macro to allow enum values to be combined and evaluated as flags.
 *  * Based on:
 *  - DEFINE_ENUM_FLAG_OPERATORS from <winnt.h>
 *  - https://stackoverflow.com/a/63031334/1624459
 */
#define MAKE_ENUM_FLAGS(TEnum)                                                      \
    inline TEnum operator~(TEnum a) {                                               \
        using TUnder = typename std::underlying_type_t<TEnum>;                      \
        return static_cast<TEnum>(~static_cast<TUnder>(a));                         \
    }                                                                               \
    inline TEnum operator|(TEnum a, TEnum b) {                                      \
        using TUnder = typename std::underlying_type_t<TEnum>;                      \
        return static_cast<TEnum>(static_cast<TUnder>(a) | static_cast<TUnder>(b)); \
    }                                                                               \
    inline TEnum operator&(TEnum a, TEnum b) {                                      \
        using TUnder = typename std::underlying_type_t<TEnum>;                      \
        return static_cast<TEnum>(static_cast<TUnder>(a) & static_cast<TUnder>(b)); \
    }                                                                               \
    inline TEnum operator^(TEnum a, TEnum b) {                                      \
        using TUnder = typename std::underlying_type_t<TEnum>;                      \
        return static_cast<TEnum>(static_cast<TUnder>(a) ^ static_cast<TUnder>(b)); \
    }                                                                               \
    inline TEnum& operator|=(TEnum& a, TEnum b) {                                   \
        using TUnder = typename std::underlying_type_t<TEnum>;                      \
        a = static_cast<TEnum>(static_cast<TUnder>(a) | static_cast<TUnder>(b));    \
        return a;                                                                   \
    }                                                                               \
    inline TEnum& operator&=(TEnum& a, TEnum b) {                                   \
        using TUnder = typename std::underlying_type_t<TEnum>;                      \
        a = static_cast<TEnum>(static_cast<TUnder>(a) & static_cast<TUnder>(b));    \
        return a;                                                                   \
    }                                                                               \
    inline TEnum& operator^=(TEnum& a, TEnum b) {                                   \
        using TUnder = typename std::underlying_type_t<TEnum>;                      \
        a = static_cast<TEnum>(static_cast<TUnder>(a) ^ static_cast<TUnder>(b));    \
        return a;                                                                   \
    }

用法

enum class Passability : std::uint8_t {
    Clear      = 0,
    GroundUnit = 1 << 1,
    FlyingUnit = 1 << 2,
    Building   = 1 << 3,
    Tree       = 1 << 4,
    Mountain   = 1 << 5,
    Blocked    = 1 << 6,
    Water      = 1 << 7,
    Coastline  = 1 << 8
};

MAKE_ENUM_FLAGS(Passability)

优点

  • 仅在显式使用时适用于选定的枚举。
  • 不使用非法reinterpret_cast
  • 无需指定底层类型。

笔记

  • 如果使用 C++ <14 ,则替换std::underlying_type_t<TEnum>为。std::underlying_type<TEnum>::type
于 2021-09-14T19:53:26.837 回答
0

您可以使用结构如下:

struct UiFlags2 {
    static const int
    FULLSCREEN = 0x00000004,               //api 16
    HIDE_NAVIGATION = 0x00000002,          //api 14
    LAYOUT_HIDE_NAVIGATION = 0x00000200,   //api 16
    LAYOUT_FULLSCREEN = 0x00000400,        //api 16
    LAYOUT_STABLE = 0x00000100,            //api 16
    IMMERSIVE_STICKY = 0x00001000;         //api 19
};

并像这样使用:

int flags = UiFlags2::FULLSCREEN | UiFlags2::HIDE_NAVIGATION;

所以你不需要int铸造,它是直接可用的。
它也是范围分离的enum class

于 2021-08-04T11:39:21.160 回答