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

Qt Code:
  1. class BaseFactory : public QObject
  2. {
  3. };
  4.  
  5. class DerivedFactory : public BaseFactory
  6. {
  7. public:
  8.  
  9. virtual ~DerivedFactory();
  10. static const DerivedFactory& instance();
  11.  
  12. private:
  13.  
  14. DerivedFactory();
  15. };
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!

Qt Code:
  1. class BaseFactory : public QObject
  2. {
  3. typedef const BaseFactory& (FactoryReg)();
  4.  
  5. /// register the factory to be called by loadAllFactories
  6. static int registerFactory( const QString& key, FactoryReg* );
  7.  
  8. static void loadAllFactories();
  9.  
  10. };
  11.  
  12. #define REGISTER_FACTORY( Key, Func ) \
  13. static const BaseFactory& instance = BaseFactory::registerFactory( #Key, Func );
  14.  
  15. class DerivedFactory : public BaseFactory
  16. {
  17. public:
  18.  
  19. virtual ~DerivedFactory();
  20. static const DerivedFactory& instance();
  21.  
  22. private:
  23.  
  24. DerivedFactory();
  25. };
  26.  
  27. // in DerivedFactory C++ file, add this line, but fail to compile of course.
  28. REGISTER_FACTORY( DerivedFactory, DerivedFactory::instance );
To copy to clipboard, switch view to plain text mode