首先,要将参数传递给方法,您需要某种超越普通 C++ 的反射框架。使用 Qt,显而易见的选择是带有它的 Qt 元对象系统QMetaObject
,但是您必须为QObject
. 之后,您需要做两件事:
1. 使构造函数可调用
默认情况下,信号和槽是可调用的,但是您想通过元对象系统调用的任何其他方法都需要明确标记为这样。示例myqobject.h:
#ifndef MYQOBJECT_H
#define MYQOBJECT_H
#include <QObject>
class MyQObject : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE MyQObject(QObject *parent = 0); // tested with empty constructor in .cpp
};
#endif // MYQOBJECT_H
2. 创建您自己的从类名字符串到QMetaObject
QMetaType
doc 说:“任何具有公共默认构造函数、公共复制构造函数和公共析构函数的类或结构都可以注册。” 这排除了 QObject,因为它们不能有复制构造函数。您需要创建自己的从名称到元对象的映射。此main.cpp中显示的示例:
#include <QCoreApplication>
#include <QtCore>
#include "myqobject.h"
// a global map for mapping strings to QMetaObjects,
// you need header file like this if you want to access it from other .cpp files:
//
// #include <QHash>
// #include <QString>
// class QMetaObject; // forward declaration, enough when only pointer is needed
// extern QHash<QString, const QMetaObject*> metaObjs;
//
QHash<QString, const QMetaObject*> metaObjs;
// optional: create a macro to avoid typing class name twice,
// #c surrounds macro argument with double quotes converting it to string
#define METAOBJS_INSERT(c) (metaObjs.insert(#c, &c::staticMetaObject))
int main()
{
METAOBJS_INSERT(MyQObject);
const QMetaObject *meta = metaObjs["MyQObject"];
qDebug() << "Class name from staticMetaObject: " << meta->className();
QObject *o = meta->newInstance(); // add constructor arguments as needed
MyQObject *mo = qobject_cast<MyQObject*>(o);
if (mo) qDebug() << "Class name from object instance: " << mo->metaObject()->className();
else qDebug() << "Instance creation failed or created wrong class!";
return 0;
}
如果您不想使用QObject
,那么您需要提出一些您自己的类似(可能更轻且没有单独的编译器步骤)机制。