假设您有一个包含类型 Item 的 std::vector 类,并且您存储继承类型的项目:武器、药水、护甲等。您如何检索作为继承类而不是基础类的项目?
最佳答案
How do you retrieve the item as the inherited class and not the base?
这表明您需要闭集多态性,它由 std::variant
或 boost::variant
提供。
using Entity = std::variant<Weapon, Potion, Armor>;
// An `Entity` is either a `Weapon`, a `Potion`, or an `Armor`.
std::vector<Entity> entities;
struct EntityVisitor
{
void operator()(Weapon&);
void operator()(Potion&);
void operator()(Armor&);
};
for(auto& e : entities)
{
std::visit(EntityVisitor{}, e);
// Call the correct overload depending on what `e` is.
}
关于c++ - 如何从 C++ 中的集合中检索多个继承类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44392924/