| 1 | // Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). |
| 2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only |
| 3 | |
| 4 | #ifndef QT3DCORE_QABSTRACTFUNCTOR_H |
| 5 | #define QT3DCORE_QABSTRACTFUNCTOR_H |
| 6 | |
| 7 | #include <Qt3DCore/qt3dcore_global.h> |
| 8 | |
| 9 | QT_BEGIN_NAMESPACE |
| 10 | |
| 11 | namespace Qt3DCore { |
| 12 | |
| 13 | // This will generate a unique id() function per type |
| 14 | // <=> 1 unique function address per type |
| 15 | template<class T> |
| 16 | struct FunctorType |
| 17 | { |
| 18 | static qintptr id() |
| 19 | { |
| 20 | // The MSVC linker can under some cases optimize all the template |
| 21 | // functions into a single function. The code below is there to ensure |
| 22 | // that the linker won't collapse all these distincts functions into one |
| 23 | static T *t = nullptr; |
| 24 | return reinterpret_cast<qintptr>(t); |
| 25 | } |
| 26 | }; |
| 27 | |
| 28 | template<class T> |
| 29 | qintptr functorTypeId() |
| 30 | { |
| 31 | return reinterpret_cast<qintptr>(&FunctorType<T>::id); |
| 32 | } |
| 33 | |
| 34 | #define QT3D_FUNCTOR(Class) \ |
| 35 | qintptr id() const override { \ |
| 36 | return Qt3DCore::functorTypeId<Class>(); \ |
| 37 | } |
| 38 | |
| 39 | |
| 40 | class Q_3DCORESHARED_EXPORT QAbstractFunctor |
| 41 | { |
| 42 | public: |
| 43 | QAbstractFunctor() = default; |
| 44 | virtual ~QAbstractFunctor(); |
| 45 | virtual qintptr id() const = 0; |
| 46 | |
| 47 | // TODO: Remove when moving a copy of this to Qt3DCore |
| 48 | template<class T> |
| 49 | const T *functor_cast(const QAbstractFunctor *other) const |
| 50 | { |
| 51 | if (other->id() == functorTypeId<T>()) |
| 52 | return static_cast<const T *>(other); |
| 53 | return nullptr; |
| 54 | } |
| 55 | private: |
| 56 | Q_DISABLE_COPY(QAbstractFunctor) |
| 57 | }; |
| 58 | |
| 59 | template<class T> |
| 60 | const T *functor_cast(const QAbstractFunctor *other) |
| 61 | { |
| 62 | if (other->id() == functorTypeId<T>()) |
| 63 | return static_cast<const T *>(other); |
| 64 | return nullptr; |
| 65 | } |
| 66 | |
| 67 | } // Qt3DCore |
| 68 | |
| 69 | QT_END_NAMESPACE |
| 70 | |
| 71 | #endif // QT3DCORE_QABSTRACTFUNCTOR_H |
| 72 | |