fork(3) download
  1. #include <iostream>
  2. #include <map>
  3. #include <memory>
  4.  
  5. struct Base {
  6. virtual ~Base() {} // do not forget this if you need polymorphism
  7. };
  8.  
  9. template <typename T>
  10. std::unique_ptr<Base> makeBase() { return std::unique_ptr<Base>(new T{}); }
  11.  
  12. using BaseMaker = std::unique_ptr<Base>(*)();
  13.  
  14. struct DerivedOne: Base {}; struct DerivedTwo: Base {};
  15.  
  16. using BaseMakerMap = std::map<std::string, BaseMaker>;
  17.  
  18. BaseMakerMap const map = { { "DerivedOne", makeBase<DerivedOne> },
  19. { "DerivedTwo", makeBase<DerivedTwo> } };
  20.  
  21. std::unique_ptr<Base> makeFromName(std::string const& n) {
  22. BaseMakerMap::const_iterator it = map.find(n);
  23.  
  24. if (it == map.end()) { return std::unique_ptr<Base>(); } // not found
  25.  
  26. BaseMaker maker = it->second;
  27.  
  28. return maker();
  29. }
  30.  
  31. int main() {
  32. makeFromName("DerivedOne");
  33. return 0;
  34. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
Standard output is empty