如何从C++中的集合中检索多个继承的类型?

Phi*_*hil 2 c++

假设你有一个std :: vector类,它包含类型Item,你存储继承类型的项目:武器,药水,护甲等.你如何检索项目作为继承的类而不是基础?

Vit*_*meo 6

如何将项目检索为继承的类而不是基础?

这表明你需要闭包多态,由std::variantor 提供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.
}
Run Code Online (Sandbox Code Playgroud)