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

    Hi.

    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();
    [...]
    

  • Qt Champions 2016

    @ankit-thakar

    I don't know why you don't like it, but the usual way is to add a dummy at the end.

    @Devopia53

    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
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.