dearn44
dearn44

Reputation: 3432

Iterate through all public methods of a class

Is it possible to iterate and print the names of all the functions that I have created in my application while using qt5?

For example lets say that I have created my own class (myClass) that contains two public slots

int add(int a, int b);
int mul(int a, int b);

What I want is later at some point to be able to print that myClass contains these two functions by name.

Upvotes: 2

Views: 1111

Answers (2)

king_nak
king_nak

Reputation: 11513

You can use QMetaObject for this, if you do some preparation. With ​methodCount() you find the number of published methods, with method(int idx) you can access the QMetaMethod objects.

The requirements are:

  1. The class must be a subclass of QObject
  2. You must use the Q_OBJECT macro in the class body
  3. The class must be compiled through moc
  4. Methods that are not a SLOT or SIGNAL must be declared using Q_INVOKABLE

Update:
For your example you can use this:

class MyClass : public QObject {
    Q_OBJECT
public slots:
   int add(int a, int b);
   int mul(int a, int b);
public:
    Q_INVOKABLE int notaslot();
};

int main(int argc, char**argv) {
    MyClass obj;
    QMetaObject *mobj = obj.metaObject();
    for (int i = 0; i < mobj->methodCount(); ++i) {
       QMetaMethod method = mobj->method(i);
       if (method.access() == QMetaMethod::Public) {
          std::cout << method.name().toStdString();
       }
    }
}

Upvotes: 4

It is not easily possible., but with some effort it might be doable.

You could customize some existing C++ compiler to do that. For example, you might customize your recent GCC compiler (g++ version 4.8 or 4.9) using MELT, but that probably would take you a week or two of work at least.

You could also run nm -C on the debug version (or at least a non-stripped version) of your executable. That would show you all the C++ symbols.

If you care only about Qt slots the moc is extracting these.

PS. Your question is unclear. Define exactly what names you want to show.

Upvotes: 0

Related Questions