QFlags: add (named) explicit conversion from/to int

There are some use cases where one may want to convert a QFlags object
from/to an integer deliberately; for instance, to store it in a
bitfield, saving some space. So far this worked by means of a implicit
conversions; instead, also add named conversions for this.

[ChangeLog][QtCore][QFlags] Added the fromInt() and toInt() functions
for explicit conversions from/to a plain integer.

Change-Id: I705559bf75b28c30b4446bb6d0753aedfc808eed
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
bb10
Giuseppe D'Angelo 2021-05-02 00:51:06 +02:00
parent f385b8827a
commit e906bb84fb
2 changed files with 21 additions and 0 deletions

View File

@ -112,6 +112,9 @@ public:
constexpr inline QFlags(std::initializer_list<Enum> flags) noexcept
: i(initializer_list_helper(flags.begin(), flags.end())) {}
constexpr static inline QFlags fromInt(Int i) noexcept { return QFlags(QFlag(i)); }
constexpr inline Int toInt() const noexcept { return i; }
constexpr inline QFlags &operator&=(int mask) noexcept { i &= mask; return *this; }
constexpr inline QFlags &operator&=(uint mask) noexcept { i &= mask; return *this; }
constexpr inline QFlags &operator&=(Enum mask) noexcept { i &= Int(mask); return *this; }

View File

@ -497,6 +497,24 @@ static_assert(sizeof(qint64) == 8, "Internal error, qint64 is misdefined");
\a on is \c false. Returns a reference to this object.
*/
/*!
\fn template <typename Enum> QFlags<Enum> QFlags<Enum>::fromInt(Int i) noexcept
\since 6.2
Constructs a QFlags object representing the integer value \a i.
*/
/*!
\fn template <typename Enum> Int QFlags<Enum>::toInt() const noexcept
\since 6.2
Returns the value stored in the QFlags object as an integer. Note
that the returned integer may be signed or unsigned, depending on
whether the enum's underlying type is signed or unsigned.
\sa Int
*/
/*!
\macro Q_DISABLE_COPY(Class)
\relates QObject