c++ - 删除继承中的代码重复?
问题描述
我写了以下代码:
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 语句,这听起来不是完美的方法。
有什么建议么?
解决方案
您可以将其设为函数模板:
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);
推荐阅读
- node.js - GitHub 显示子模块而不是子文件夹
- vue.js - 无法读取未定义的属性“长度” - 为什么 DOM 在“创建”之前尝试加载?
- python - 尝试点击亚马逊畅销书排名(Python)
- python - Seaborn displot - 在一个图中绘制多个图
- python - 如何将 OTP 发送到 Django 中的电话号码?
- python-3.x - 向数据框熊猫添加行
- php - 如何从 PHP 上的 $_GET 值向数据库表中插入数据
- html - 在带有 Python3 的树莓中为 arduino 使用 HTML
- c# - While/for 循环直到出现特定条件
- c# - 从 NET Core Web 应用程序调用 Microsoft Graph SDK 时出现 MsalUiRequiredException