From 9a94c4a415179377197f02580ea8fbcb0c5ce517 Mon Sep 17 00:00:00 2001 From: Giuseppe D'Angelo Date: Mon, 17 May 2021 12:51:26 +0200 Subject: [PATCH] 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 --- src/corelib/global/qglobal.cpp | 9 +++++++++ src/corelib/global/qglobal.h | 7 +++++++ .../corelib/global/qglobal/tst_qglobal.cpp | 20 +++++++++++++++++++ 3 files changed, 36 insertions(+) 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"