简体   繁体   中英

Why am I getting this bit-wise operation error when using a custom QFlags implementation?

I created my own custom QFlags enumeration...

class A
{
  ...

  enum class PrimitiveTypeFlag : unsigned int {
    Unknown = 0x0,
    Bool = 0x1,
    Float = 0x2,
    Double = 0x4,
    Int8 = 0x8,
    UInt8 = 0x10,
    Int16 = 0x20,
    UInt16 = 0x40,
    Int32 = 0x80,
    UInt32 = 0x100,
    Int64 = 0x200,
    UInt64 = 0x400,
    StatsDataArray = 0x800,
    NeighborList = 0x1000,
    StringArray = 0x2000,
    NumericalPrimitives = 0x07FE,
    Any = 0x3FFF
  };
  Q_DECLARE_FLAGS(PrimitiveTypeFlags, PrimitiveTypeFlag)
  ...
  ...
};
Q_DECLARE_OPERATORS_FOR_FLAGS(A::PrimitiveTypeFlags)

When I instantiate an instance of PrimitiveTypeFlags, all flags are turned on.

A::PrimitiveTypeFlags pFlags;
pFlags.setFlag(A::PrimitiveTypeFlag::StringArray, false);

When I execute the block of code above to turn off the StringArray flag, I get this error:

invalid argument type 'A::PrimitiveTypeFlag' to unary expression.

If I simply execute ~A::PrimitiveTypeFlag::StringArray , I also get the same error.

Why do I get this error, and how do I fix it?

Thanks in advance.

enum classes are meant to be used as pure enums, which makes them safer to use by forbidding implicit conversions to their underlying type. This is hitting you here, because the QT macros expect to be able to perform bit operations on the values passed in.

You should be able to fix this by using pre-C++11 enum declarations:

class A
{
  ...

  enum PrimitiveTypeFlag : unsigned int {
    Unknown = 0x0,
    Bool = 0x1,
    Float = 0x2,
    Double = 0x4,
    Int8 = 0x8,
    UInt8 = 0x10,
    Int16 = 0x20,
    UInt16 = 0x40,
    Int32 = 0x80,
    UInt32 = 0x100,
    Int64 = 0x200,
    UInt64 = 0x400,
    StatsDataArray = 0x800,
    NeighborList = 0x1000,
    StringArray = 0x2000,
    NumericalPrimitives = 0x07FE,
    Any = 0x3FFF
  };
  Q_DECLARE_FLAGS(PrimitiveTypeFlags, PrimitiveTypeFlag)
  ...
  ...
};
Q_DECLARE_OPERATORS_FOR_FLAGS(A::PrimitiveTypeFlags)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM