存储指向基 class 的指针的最佳方法,但能够使用派生的 class 函数

Best way to store a pointer to base class, but be able to use derived class functions

我有一个Cell,可以存储CellContent类型的对象。 CellContent 必须是虚拟 class。从 CellContent 我必须得出 classes EnemyItem。所以想法是在 Cell 中存储一个指向 CellContent 的指针。问题是:在这种情况下,存储指向派生 class 的指针的最佳方法是什么?

我目前的解决方案不是一个优雅的解决方案,我想改进它。

class Cell
{
public:
  template<class T> void setCellContent(std::shared_ptr<T> cellContent)
  {
    _cellContent = std::dyanmic_pointer_cast<CellContent>(cellContent);

    if (std::is_same<T, Enemy>::value = true) {
      _cellContentType = CellContentType::ENEMY;
    } else if (std::is_same<T, Item>::value = true) {
      _cellContentType = CellContentType::ITEM;      
    }
  }

  template<class T> std::shared_ptr<T> getCellContent()
  {  
    return std::dynamic_pointer_cast<T>(_cellContent);
  }

  CellContentType getCellContentType()
  {
    return _cellContentType;
  }

  std::shared_ptr<CellContent> _cellContent;
  CellContentType _cellContentType;
}

int main()
{
  auto enemy = std::make_shared<Enemy>();

  Cell cell;
  cell.setCellContent<Enemy>(enemy);

  if (CellContentType::ENEMY == cell.getCellContentType()) {
    cell.getCellContent<Enemy>();
  } else if (CellContentType::ITEM == cell.getCellContentType()) {
    cell.getCellContent<Item>();
  }
}

如何避免在 main 中使用 if 这个丑陋的 if?

导出的所有函数-class,其中:

  • 需要可调用,
  • 虽然变量是base-class类型,
  • 但是没有从基础-class-类型手动转换为派生-class-类型,

应该在 base-class 中声明为 virtual(并在 derived-class 中被覆盖)。