From 6ff7f71c31495ff00a6ce3736152b28ededb8428 Mon Sep 17 00:00:00 2001 From: Volker Hilsheimer Date: Tue, 1 Apr 2025 12:52:58 +0200 Subject: [PATCH] qgraphicsitem_cast: replace runtime with compile-time check Specialize the cast template for QGraphicsItem, where we can skip the runtime comparisons of the type. In addition, replace the runtime check for QGraphicsItem::Type with a compile time check in the main template. We need to do both so that we correctly cast up to QGraphicsItem for custom item types that don't provide their own Type alias. Pick-to: 6.8 Change-Id: Ic1bff3404fe890747865ce1349cddbcfebb3b77b Reviewed-by: Axel Spoerl (cherry picked from commit 7af5912e61160681be736ff07a1cd0a0f6b28944) Reviewed-by: Qt Cherry-pick Bot --- src/widgets/graphicsview/qgraphicsitem.h | 26 ++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/src/widgets/graphicsview/qgraphicsitem.h b/src/widgets/graphicsview/qgraphicsitem.h index f82c600b3a3..8819813363a 100644 --- a/src/widgets/graphicsview/qgraphicsitem.h +++ b/src/widgets/graphicsview/qgraphicsitem.h @@ -969,15 +969,33 @@ private: template inline T qgraphicsitem_cast(QGraphicsItem *item) { typedef typename std::remove_cv::type>::type Item; - return int(Item::Type) == int(QGraphicsItem::Type) - || (item && int(Item::Type) == item->type()) ? static_cast(item) : nullptr; + constexpr int ItemType = int(Item::Type); + if constexpr (int(Item::Type) == int(QGraphicsItem::Type)) + return static_cast(item); + else + return (item && ItemType == item->type()) ? static_cast(item) : nullptr; } template inline T qgraphicsitem_cast(const QGraphicsItem *item) { typedef typename std::remove_cv::type>::type Item; - return int(Item::Type) == int(QGraphicsItem::Type) - || (item && int(Item::Type) == item->type()) ? static_cast(item) : nullptr; + constexpr int ItemType = int(Item::Type); + if constexpr (ItemType == int(QGraphicsItem::Type)) + return static_cast(item); + else + return (item && ItemType == item->type()) ? static_cast(item) : nullptr; +} + +template <> +inline QGraphicsItem *qgraphicsitem_cast(QGraphicsItem *item) +{ + return item; +} + +template <> +inline const QGraphicsItem *qgraphicsitem_cast(const QGraphicsItem *item) +{ + return item; } #ifndef QT_NO_DEBUG_STREAM