fork download
  1. #include <iostream>
  2. #include <map>
  3.  
  4. template < class Base, class Key, typename ObjectCreator = Base* (*)()>
  5. class ObjectFactory
  6. {
  7. public:
  8. bool registerCreator( const Key& id, ObjectCreator creator)
  9. {
  10. return associations_.insert( typename IdToObjectMap::value_type(id, creator)).second != 0;
  11. }
  12. private:
  13. typedef std::map<Key, ObjectCreator> IdToObjectMap;
  14. IdToObjectMap associations_;
  15. };
  16.  
  17. struct AbstractResource {};
  18.  
  19. template <typename T>
  20. struct SingletonHolder
  21. {
  22. static T Instance() { return T(); }
  23. };
  24. typedef SingletonHolder < ObjectFactory < AbstractResource, const char*, AbstractResource* (*)()> > ResourceFactory;
  25.  
  26. template <class DerivedType>
  27. class ResourceBase
  28. {
  29. public:
  30. virtual ~ResourceBase() {}
  31. static bool registerWithFactory();
  32. static bool isInitialized() { return _Initialized; }
  33. protected:
  34. ResourceBase() {}
  35. private:
  36. static const bool _Initialized;
  37. };
  38.  
  39. template <class DerivedType>
  40. const bool ResourceBase<DerivedType>::_Initialized = ResourceBase<DerivedType>::registerWithFactory();
  41.  
  42. template<class DerivedType>
  43. bool ResourceBase<DerivedType>::registerWithFactory()
  44. {
  45. if (! _Initialized)
  46. {
  47. return ResourceFactory::Instance().template registerCreator<DerivedType> (DerivedType::className() , &DerivedType::allocate);
  48. }
  49. }
  50.  
  51. struct FileManager: public ResourceBase<FileManager>, AbstractResource {
  52. static const char* className() { return "FileManager"; }
  53. static AbstractResource* allocate() { return new FileManager; };
  54. };
  55.  
  56. int main()
  57. {
  58. FileManager f;
  59. std::cout << f.isInitialized() << std::endl;
  60. return 0;
  61. }
  62.  
Compilation error #stdin compilation error #stdout 0.01s 2720KB
stdin
Standard input is empty
compilation info
prog.cpp: In static member function ‘static bool ResourceBase<DerivedType>::registerWithFactory() [with DerivedType = FileManager]’:
prog.cpp:40:   instantiated from ‘const bool ResourceBase<FileManager>::_Initialized’
prog.cpp:32:   instantiated from ‘static bool ResourceBase<DerivedType>::isInitialized() [with DerivedType = FileManager]’
prog.cpp:59:   instantiated from here
prog.cpp:47: error: no matching function for call to ‘ObjectFactory<AbstractResource, const char*, AbstractResource* (*)()>::registerCreator(const char*, AbstractResource* (*)())’
stdout
Standard output is empty