我应该使用std :: optional还是继承方法添加一个可选的类成员?

时间:2020-02-09 20:58:28

标签: c++ inheritance architecture optional design-decisions

我有class Item,这本身就是没有兴趣的人。但是,我需要一些Item才能像衣服或武器一样装备,还需要另外存储一个enum class Limb对象,该对象代表可以装备它们的身体部位。而且,普通Item必须与“齿轮” Item一起放置在单个STL容器中,并可能稍后作为“齿轮” Item取出。我在这里看到两个选项:继承

class Item { /* ... */ };
class Gear : public Item {
  Limb limb;
// ...
};
std::vector<std::unique_ptr<Item>> items;
std::unique_ptr<Gear> gear = // dynamic cast items[...] and check for success

std::optional

class Item {
  std::optional<Limb> limb; // if equippable, limb.has_value() == true
// ...
};
std::vector<Item> items;
Item gear = // get items[...] and check limb.has_value()

当函数需要Gear(而不仅仅是Item)而不是其中的运行时assert(item.is_gear())时,我喜欢第一个扩展性和编译时类型检查工具。

第二个在速度(即使没有预期的性能问题的情况下我也很在意)和设计的自然性方面似乎更好:我不需要了解任何其他class和特殊使用工程Item时的用例(例如,使它的析构函数virtual像第一个变体一样会破坏它),这似乎是干净无辜的设计。

哪个决定会更好,为什么?还是有更好的解决方案?

0 个答案:

没有答案