Hi,
I have a base class for a base plugin factory (BaseFactory), and many derived factories (DerivedFactory). In each DerivedFactory, there is a static singleton DerivedFactory::instance() as in the following code
{
};
class DerivedFactory : public BaseFactory
{
public:
virtual ~DerivedFactory();
static const DerivedFactory& instance();
private:
DerivedFactory();
};
class BaseFactory : public QObject
{
};
class DerivedFactory : public BaseFactory
{
public:
virtual ~DerivedFactory();
static const DerivedFactory& instance();
private:
DerivedFactory();
};
To copy to clipboard, switch view to plain text mode
Each DerivedFactory::instance() needed to be called immediately after the QApplication is created so the factory is ready to produce object base on class name.
The problem is I have quite a few of those factories, so I hope to force programmers to register the derived factory into the base by some macros, so the base factory will call all DerivedFactory::instance() in one go. This will also avoid some derived factory not be initialized, causing program to crash when restoring previously saved session (because factory has not loaded the plugin yet).
I try following way, and obviously, the function prototype does not match. How can I achieve this goal? Many thanks!
{
typedef const BaseFactory& (FactoryReg)();
/// register the factory to be called by loadAllFactories
static int registerFactory( const QString& key, FactoryReg* );
static void loadAllFactories();
};
#define REGISTER_FACTORY( Key, Func ) \
static const BaseFactory& instance = BaseFactory::registerFactory( #Key, Func );
class DerivedFactory : public BaseFactory
{
public:
virtual ~DerivedFactory();
static const DerivedFactory& instance();
private:
DerivedFactory();
};
// in DerivedFactory C++ file, add this line, but fail to compile of course.
REGISTER_FACTORY( DerivedFactory, DerivedFactory::instance );
class BaseFactory : public QObject
{
typedef const BaseFactory& (FactoryReg)();
/// register the factory to be called by loadAllFactories
static int registerFactory( const QString& key, FactoryReg* );
static void loadAllFactories();
};
#define REGISTER_FACTORY( Key, Func ) \
static const BaseFactory& instance = BaseFactory::registerFactory( #Key, Func );
class DerivedFactory : public BaseFactory
{
public:
virtual ~DerivedFactory();
static const DerivedFactory& instance();
private:
DerivedFactory();
};
// in DerivedFactory C++ file, add this line, but fail to compile of course.
REGISTER_FACTORY( DerivedFactory, DerivedFactory::instance );
To copy to clipboard, switch view to plain text mode
Bookmarks