fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <memory>
  4. #include <stdexcept>
  5.  
  6. class Base
  7. {
  8. public:
  9. //...
  10. virtual int getId() const = 0;
  11. };
  12.  
  13. class Derived1: public Base
  14. {
  15. public:
  16. //...
  17. int getId() const override { return 0; }
  18. };
  19.  
  20. class Derived2: public Base
  21. {
  22. public:
  23. //...
  24. int getId() const override { return 1; }
  25. };
  26.  
  27. //...
  28.  
  29. using createFunc = std::shared_ptr<Base>(*)();
  30.  
  31. static std::map<int, createFunc> myMap
  32. {
  33. {0, []() -> std::shared_ptr<Base> { return std::make_shared<Derived1>(); }},
  34. {1, []() -> std::shared_ptr<Base> { return std::make_shared<Derived2>(); }}
  35. //...
  36. };
  37.  
  38. static std::shared_ptr<Base> createInstance(int id)
  39. {
  40. auto iter = myMap.find(id);
  41. if (iter == myMap.end())
  42. throw std::out_of_range("Unknown id");
  43. return iter->second();
  44. }
  45.  
  46. static int getId(Base* instance)
  47. {
  48. return instance->getId();
  49. }
  50.  
  51. int main()
  52. {
  53. auto inst1 = createInstance(0);
  54. std::cout << getId(inst1.get()) << std::endl;
  55.  
  56. auto inst2 = createInstance(1);
  57. std::cout << getId(inst2.get()) << std::endl;
  58.  
  59. try
  60. {
  61. auto inst3 = createInstance(3);
  62. std::cout << getId(inst3.get()) << std::endl;
  63. }
  64. catch (const std::exception &e)
  65. {
  66. std::cout << e.what() << std::endl;
  67. }
  68.  
  69. return 0;
  70. }
Success #stdin #stdout 0s 4312KB
stdin
Standard input is empty
stdout
0
1
Unknown id