Long live qToUnderlying

"Cherry-pick" of C++2b's std::to_underlying.

[ChangeLog][QtCore][QtGlobal] The qToUnderlying function has been
added, to convert an value of enumeration type to its underlying
value.

Change-Id: Ia46bd8e4496e55174171ac2f0799eacbcca02cf9
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
This commit is contained in:
Giuseppe D'Angelo 2021-05-17 12:51:26 +02:00
parent 8b8ff64be2
commit 9a94c4a415
3 changed files with 36 additions and 0 deletions

View File

@ -3877,6 +3877,15 @@ bool qunsetenv(const char *varName)
that qExchange() returns a non-const object, so Qt containers may detach.
*/
/*!
\fn template <typename Enum> std::underlying_type_t<Enum> qToUnderlying(Enum e)
\relates <QtGlobal>
\since 6.2
Converts the enumerator \e to the equivalent value expressed in its
enumeration's underlying type.
*/
/*!
\macro QT_TR_NOOP(sourceText)
\relates <QtGlobal>

View File

@ -1177,6 +1177,13 @@ constexpr T qExchange(T &t, U &&newValue)
return old;
}
// like std::to_underlying
template <typename Enum>
constexpr std::underlying_type_t<Enum> qToUnderlying(Enum e) noexcept
{
return static_cast<std::underlying_type_t<Enum>>(e);
}
#ifdef __cpp_conditional_explicit
#define Q_IMPLICIT explicit(false)
#else

View File

@ -60,6 +60,7 @@ private slots:
void qRoundDoubles_data();
void qRoundDoubles();
void PRImacros();
void testqToUnderlying();
};
extern "C" { // functions in qglobal.c
@ -698,5 +699,24 @@ void tst_QGlobal::PRImacros()
}
}
void tst_QGlobal::testqToUnderlying()
{
enum class E {
E1 = 123,
E2 = 456,
};
static_assert(std::is_same_v<decltype(qToUnderlying(E::E1)), int>);
QCOMPARE(qToUnderlying(E::E1), 123);
QCOMPARE(qToUnderlying(E::E2), 456);
enum EE : unsigned long {
EE1 = 123,
EE2 = 456,
};
static_assert(std::is_same_v<decltype(qToUnderlying(EE1)), unsigned long>);
QCOMPARE(qToUnderlying(EE1), 123UL);
QCOMPARE(qToUnderlying(EE2), 456UL);
}
QTEST_APPLESS_MAIN(tst_QGlobal)
#include "tst_qglobal.moc"