动态投射或第二个对象容器?

时间:2012-04-15 04:17:40

标签: c++ inheritance casting polymorphism

我有一个对象组的模板类,其他更专业的组可以从中派生(使用它作为复合模式)。无论如何,我的Group类处理所有实际的组代码。

现在我有一个容器,容纳T类型的对象,但我还需要通过交叉转换访问另一个基类的接口。你推荐我有两个接口的容器,或者当我循环通过第一个容器时,只有dynamic_cast每个对象吗?

class Sim_object {
  add(Sim_object_sp_t object)
  remove(Sim_object_sp_t object)
};

class Group<T> : public class Sim_object {
  add(Sim_object_sp_t object)
  remove(Sim_object_sp_t object)
  map<T>
  protected iterators begin(), end() (for use by Ship_group to use for dock, attack, move functions)
  // looking to add map<Sim_object> to prevent casting from T to Sim_object in Add/Remove but still give derived classes access to map<T> iterators.
};

class IShip {
  dock() = 0
  attack() = 0
  move() = 0
};

class Ship_group : public Group<IShip>, public IShip {
  dock()  // uses iterators provided by Group to loop through and call dock()
  attack() // same as dock
  move() // same as dock
};

class Ship : public Sim_object, public IShip {
  dock()
  attack()
  move()
};

因此,我需要在Group中访问的两个接口是T(本例中为IShip)和Sim_object。

组中的示例:

template<typename T>
void Group<T>::add(Sim_object_sp_t object) { 
  if (object->get_parent())
    object->get_parent()->remove(object);

  std::tr1::shared_ptr<T> t_object = std::tr1::dynamic_pointer_cast<T>(object);
  if (!t_object)
    throw Error("Failed to cast to type T");

  objects[object->get_name()] = t_object;
  object->set_parent(shared_from_this());
}

Ship_group示例:

void Ship_group::set_destination_position_and_speed(Point destination_position, double speed) {
  for (Iterator it = begin(); it != end(); ++it) {
    try {
      it->second->set_destination_position_and_speed(destination_position, speed);
    } catch (const Error& e) {
      cout << it->second->get_name() << " -- " << e.msg << endl;
    }
  }
}

1 个答案:

答案 0 :(得分:0)

可能是class Group<T>内的嵌套类型:

class Group<T> : public class Sim_object {
    class Specialized_Sim_Object : public T, public Sim_object {}
    void add(Specialized_Sim_Object * object) {
        objects[object->get_name()] = object;
    }
}

在这种情况下,shared_ptr可能不是必需的 - 当Ship_group遍历地图时,类型已经保证为IShip