首页 > 解决方案 > 删除继承中的代码重复?

问题描述

我写了以下代码:

std::shared_ptr<mtm::Character>
Game::makeCharacter(CharacterType type, Team team, units_t health, units_t ammo, units_t range, units_t power) {
    if (health <= 0 || ammo < 0 || range < 0 || power < 0)
    {
        throw mtm::IllegalArgument();
    }
    std::shared_ptr<Character> out = nullptr;
    if (type == SOLDIER)
    {
        out = std::shared_ptr<Character>(new mtm::Soldier(team, health, ammo, range, power));
    }
    if (type == MEDIC)
    {
        out = std::shared_ptr<Character>(new mtm::Medic(team, health, ammo, range, power));
    }
    return out;
}

如您所见,我有某种代码重复,如果有 100 种类型怎么办...我将不得不编写 100 个 if 语句,这听起来不是完美的方法。

有什么建议么?

标签: c++classc++11inheritancepolymorphism

解决方案


您可以将其设为函数模板:

template<typename C>
std::shared_ptr<mtm::Character>
Game::makeCharacter(Team team, units_t health, units_t ammo, units_t range, units_t power) {
    if (health <= 0 || ammo < 0 || range < 0 || power < 0)
    {
        throw mtm::IllegalArgument();
    }
    return std::make_shared<C>(team, health, ammo, range, power);
}

并称之为:

auto res = Game::makeCharacter<Soldier>(t, h, a, r, p);

推荐阅读