我有一个用于 Group 对象的模板类,其他更专业的组可以从中派生(将其用于复合模式)。无论如何,我的 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;
}
}
}