fork(1) download
  1. #include <iostream>
  2. #include <unordered_map>
  3. #include <string>
  4.  
  5. class Component
  6. {
  7. public:
  8. virtual Component* Clone() const = 0;
  9. virtual std::string ComponentType() const = 0;
  10. };
  11.  
  12. class Player : public Component
  13. {
  14. public:
  15. Component* Clone() const
  16. {
  17. return new Player(*this);
  18. }
  19.  
  20. std::string ComponentType() const
  21. {
  22. return "PlayerComponent";
  23. }
  24. };
  25.  
  26. class GameObject : public Component
  27. {
  28. public:
  29. Component* Clone() const
  30. {
  31. return new GameObject(*this);
  32. }
  33.  
  34. std::string ComponentType() const
  35. {
  36. return "GameObjectComponent";
  37. }
  38. };
  39.  
  40. class SomeContainer
  41. {
  42. private:
  43. std::unordered_map<std::string, Component*> m_components;
  44.  
  45. public:
  46. void AddComponent(Component* theComponent)
  47. {
  48. if (m_components.find(theComponent->ComponentType()) == m_components.end())
  49. {
  50. m_components.insert(std::make_pair(theComponent->ComponentType(), theComponent));
  51. }
  52. else
  53. {
  54. std::cout << "I didn't add this " << theComponent->ComponentType();
  55. std::cout << " as I already have one" << std::endl;
  56. }
  57. }
  58. };
  59.  
  60. int main()
  61. {
  62. auto someContainer = SomeContainer();
  63. auto aPlayer = new Player();
  64.  
  65. someContainer.AddComponent(aPlayer);
  66. someContainer.AddComponent(new GameObject());
  67. someContainer.AddComponent(aPlayer->Clone());
  68.  
  69. return 0;
  70. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
I didn't add this PlayerComponent as I already have one