diff --git a/src/corelib/global/qglobal.cpp b/src/corelib/global/qglobal.cpp index 9f18e9a8948..b320faa72fb 100644 --- a/src/corelib/global/qglobal.cpp +++ b/src/corelib/global/qglobal.cpp @@ -3877,6 +3877,15 @@ bool qunsetenv(const char *varName) that qExchange() returns a non-const object, so Qt containers may detach. */ +/*! + \fn template std::underlying_type_t qToUnderlying(Enum e) + \relates + \since 6.2 + + Converts the enumerator \e to the equivalent value expressed in its + enumeration's underlying type. +*/ + /*! \macro QT_TR_NOOP(sourceText) \relates diff --git a/src/corelib/global/qglobal.h b/src/corelib/global/qglobal.h index 52accb80317..481ee695caa 100644 --- a/src/corelib/global/qglobal.h +++ b/src/corelib/global/qglobal.h @@ -1177,6 +1177,13 @@ constexpr T qExchange(T &t, U &&newValue) return old; } +// like std::to_underlying +template +constexpr std::underlying_type_t qToUnderlying(Enum e) noexcept +{ + return static_cast>(e); +} + #ifdef __cpp_conditional_explicit #define Q_IMPLICIT explicit(false) #else diff --git a/tests/auto/corelib/global/qglobal/tst_qglobal.cpp b/tests/auto/corelib/global/qglobal/tst_qglobal.cpp index 5547f832ffd..3d8759fba58 100644 --- a/tests/auto/corelib/global/qglobal/tst_qglobal.cpp +++ b/tests/auto/corelib/global/qglobal/tst_qglobal.cpp @@ -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); + QCOMPARE(qToUnderlying(E::E1), 123); + QCOMPARE(qToUnderlying(E::E2), 456); + + enum EE : unsigned long { + EE1 = 123, + EE2 = 456, + }; + static_assert(std::is_same_v); + QCOMPARE(qToUnderlying(EE1), 123UL); + QCOMPARE(qToUnderlying(EE2), 456UL); +} + QTEST_APPLESS_MAIN(tst_QGlobal) #include "tst_qglobal.moc"