Last active
March 6, 2023 10:52
-
-
Save hasselmm/9cc5fb4404b52d28560b86cb468ca707 to your computer and use it in GitHub Desktop.
Switch statement on C++ type in Qt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| constexpr quint64 label(const char *const s, size_t shift = 0) | |
| { | |
| if (s[0] == '\0') | |
| return 0; // end of string | |
| if (shift == 56) | |
| return 0; // avoid integer overflow | |
| return (static_cast<quint64>(s[0]) << shift) ^ label(&s[1], shift + 1); | |
| } | |
| template<typename T> | |
| constexpr auto label() | |
| { | |
| return label(QMetaType::fromType<T>().name()); | |
| } | |
| constexpr auto label(QMetaType metaType) | |
| { | |
| return label(metaType.name()); | |
| } | |
| static_assert(label<int>()); | |
| static_assert(label<int>() != label<uint>()); | |
| void demo(const QObject *obj) | |
| { | |
| switch (label(obj->metaObject()->metaType())) { | |
| case label<QLabel>(): | |
| qInfo() << "This is a label"; | |
| break; | |
| case label<QButton>(): | |
| qInfo() << "This is a button"; | |
| break; | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why
switchinstead of the usual if-else-forest of dynamic casts?switchstatements, which is not supported for if-else-forests.