Guest User

Untitled

a guest
Nov 10th, 2015
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. enum class UnitType { WARRIOR, WIZARD };
  5. class Unit
  6. {
  7. protected:
  8.     Unit(int hp)
  9.         : m_hp(hp)
  10.     { }
  11.  
  12. public:
  13.  
  14.     virtual void cast() const = 0;
  15.     virtual ~Unit() { }
  16.  
  17. protected:
  18.     int m_hp;
  19. };
  20.  
  21. class Warrior : public Unit
  22. {
  23. public:
  24.     Warrior(int hp)
  25.         : Unit(hp)
  26.     {
  27.         std::cout << "Warrior arrives to battlefield with " << m_hp << "hp." << std::endl;
  28.     }
  29.  
  30.     void cast() const override
  31.     {
  32.         std::cout << "Warrior's charge strikes 20dmg!" << std::endl;
  33.     }
  34.  
  35.     ~Warrior()
  36.     {
  37.         std::cout << "Warrior dies" << std::endl;
  38.     }
  39. };
  40.  
  41. class Wizard : public Unit
  42. {
  43. public:
  44.     Wizard(int hp)
  45.         : Unit(hp)
  46.     {
  47.         std::cout << "Wizard arrives to battlefield with " << m_hp << "hp." << std::endl;
  48.     }
  49.    
  50.     Wizard(int hp, std::string greeting)
  51.         : Unit(hp)
  52.     {
  53.         std::cout << greeting << std::endl;
  54.     }
  55.  
  56.     void cast() const override
  57.     {
  58.         std::cout << "Wizard's fireball strikes 20dmg!" << std::endl;
  59.     }
  60.  
  61.     ~Wizard()
  62.     {
  63.         std::cout << "They should regret the day I died." << std::endl;
  64.     }
  65.    
  66. };
  67.  
  68. auto delUnit = [](Unit* unit)
  69. {
  70.     std::cout << "I got fatal damage! Dying right now." << std::endl;
  71.     delete unit;
  72. };
  73.  
  74. template<typename... Ts>
  75. std::unique_ptr<Unit, decltype(delUnit)>
  76. makeUnit(UnitType type, Ts&&... params)
  77. {
  78.     std::unique_ptr<Unit, decltype(delUnit)>
  79.     pUnit(nullptr, delUnit);
  80.  
  81.     if (type == UnitType::WARRIOR)
  82.     {
  83.         pUnit.reset(new Warrior(std::forward<Ts>(params)...));
  84.     }
  85.     else if (type == UnitType::WIZARD)
  86.     {
  87.         pUnit.reset(new Wizard(std::forward<Ts>(params)...));
  88.     }
  89.     return pUnit;
  90. }
  91.  
  92. int main()
  93. {
  94.     auto wiz = makeUnit(UnitType::WIZARD, 150, "Hello there!");
  95.     auto kek = makeUnit(UnitType::WARRIOR, 50);
  96.  
  97.     wiz->cast();
  98.     war->cast();
  99.     wiz->cast();
  100.  
  101.     return 0;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment