Important: Please read the Qt Code of Conduct -

How to get no of items defined in enum ?

  • 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...

  • @ankit-thakar


    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
          MyClass(QObject *parent = 0);
          enum Priority { High, Low, VeryHigh, VeryLow };
    #include <QMetaEnum>
    QMetaEnum   en = QMetaEnum::fromType<Priority>();
    qDebug() << << en.keyCount();

  • Moderators


    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.

Log in to reply