Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <memory>
- enum class UnitType { WARRIOR, WIZARD };
- class Unit
- {
- protected:
- Unit(int hp)
- : m_hp(hp)
- { }
- public:
- virtual void cast() const = 0;
- virtual ~Unit() { }
- protected:
- int m_hp;
- };
- class Warrior : public Unit
- {
- public:
- Warrior(int hp)
- : Unit(hp)
- {
- std::cout << "Warrior arrives to battlefield with " << m_hp << "hp." << std::endl;
- }
- void cast() const override
- {
- std::cout << "Warrior's charge strikes 20dmg!" << std::endl;
- }
- ~Warrior()
- {
- std::cout << "Warrior dies" << std::endl;
- }
- };
- class Wizard : public Unit
- {
- public:
- Wizard(int hp)
- : Unit(hp)
- {
- std::cout << "Wizard arrives to battlefield with " << m_hp << "hp." << std::endl;
- }
- Wizard(int hp, std::string greeting)
- : Unit(hp)
- {
- std::cout << greeting << std::endl;
- }
- void cast() const override
- {
- std::cout << "Wizard's fireball strikes 20dmg!" << std::endl;
- }
- ~Wizard()
- {
- std::cout << "They should regret the day I died." << std::endl;
- }
- };
- auto delUnit = [](Unit* unit)
- {
- std::cout << "I got fatal damage! Dying right now." << std::endl;
- delete unit;
- };
- template<typename... Ts>
- std::unique_ptr<Unit, decltype(delUnit)>
- makeUnit(UnitType type, Ts&&... params)
- {
- std::unique_ptr<Unit, decltype(delUnit)>
- pUnit(nullptr, delUnit);
- if (type == UnitType::WARRIOR)
- {
- pUnit.reset(new Warrior(std::forward<Ts>(params)...));
- }
- else if (type == UnitType::WIZARD)
- {
- pUnit.reset(new Wizard(std::forward<Ts>(params)...));
- }
- return pUnit;
- }
- int main()
- {
- auto wiz = makeUnit(UnitType::WIZARD, 150, "Hello there!");
- auto kek = makeUnit(UnitType::WARRIOR, 50);
- wiz->cast();
- war->cast();
- wiz->cast();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment