How to get no of items defined in enum ?
-
wrote on 18 Aug 2016, 02:08 last edited by
Hello All,
I got one situation in which i want total no. of items defined in enum.
for e.g.enum temp
{ A, B, C }Now I want it should return value 3.
I googled it how to do it but everybody did like patch work either defining one extra last element in enum or by subtracting the value from LAST - FIRST + 1 .But above mentioned solution is not perfect.
Does anybody have an idea how to do this ?
Thanks in advance...
-
Hello All,
I got one situation in which i want total no. of items defined in enum.
for e.g.enum temp
{ A, B, C }Now I want it should return value 3.
I googled it how to do it but everybody did like patch work either defining one extra last element in enum or by subtracting the value from LAST - FIRST + 1 .But above mentioned solution is not perfect.
Does anybody have an idea how to do this ?
Thanks in advance...
wrote on 18 Aug 2016, 02:35 last edited byHi.
Yes. You can use the Qt's Meta-Object System(a called QMetaEnum). You can also use QMetaEnum::fromType() to get the QMetaEnum.
Something like this:
class MyClass : public QObject { Q_OBJECT public: MyClass(QObject *parent = 0); ~MyClass(); enum Priority { High, Low, VeryHigh, VeryLow }; Q_ENUM(Priority) }; [...] #include <QMetaEnum> QMetaEnum en = QMetaEnum::fromType<Priority>(); qDebug() << en.name() << en.keyCount(); [...]
-
Hello All,
I got one situation in which i want total no. of items defined in enum.
for e.g.enum temp
{ A, B, C }Now I want it should return value 3.
I googled it how to do it but everybody did like patch work either defining one extra last element in enum or by subtracting the value from LAST - FIRST + 1 .But above mentioned solution is not perfect.
Does anybody have an idea how to do this ?
Thanks in advance...
I don't know why you don't like it, but the usual way is to add a dummy at the end.
My issue with that solution is that you're getting the information at runtime, instead of at compile time. There is increased chance of errors and there isn't really a need to inquire the meta object system in this case.
1/3