Advertisement
SRD

abstract class

SRD
Jul 14th, 2018
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. /*
  2. I have a base class (Element) which just became an abstract class and breaks registration for my factory. Does anyone see a way for this template to not allocate the abstract class Element, rather, the derived class.
  3. */
  4.  
  5. EFactory::EFactory() { }
  6.  
  7. EFactory::~EFactory()
  8. {
  9.     factoryRegistry.clear();
  10. }
  11.  
  12. EFactory* EFactory::instance()
  13. {
  14.     static EFactory factory;
  15.  
  16.     return &factory;
  17. }
  18.  
  19. void EFactory::registerFunction(std::string name,
  20.     std::function<Element* ()> factoryFunction)
  21. {
  22.     factoryRegistry[name] = factoryFunction;
  23. }
  24.  
  25. std::shared_ptr<Element> EFactory::create(std::string name)
  26. {
  27.     Element* instance = nullptr;
  28.  
  29.     auto it = factoryRegistry.find(name);
  30.  
  31.     if (it != factoryRegistry.end())
  32.         instance = it->second();
  33.  
  34.     if (instance != nullptr)
  35.         return std::shared_ptr<Element>(instance);
  36.     else
  37.         return nullptr;
  38. }
  39.  
  40.  
  41. template<typename T>
  42. class Registrar
  43. {
  44.     public:
  45.         Registrar(std::string name)
  46.         {
  47.  
  48.             EFactory::instance()->registerFunction(name,
  49.                 [] (void) -> Element* { return new T(); });
  50.  
  51.         // The error points to the line above
  52.         }
  53. };
  54.  
  55. /* Here's the compile error ...
  56.                        
  57. triangle.cpp:5:48:   required from here registrar.h:18:45: error: invalid new-expression of abstract class type ‘Triangle’                                  
  58.      [] (void) -> Element* { return new T(); });                      
  59.                                              ^~~~~~~  
  60. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement