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

标签 c++

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

最佳答案

How do you retrieve the item as the inherited class and not the base?

这表明您需要闭集多态性,它由 std::variantboost::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/

相关文章:

c++ - 使用delete后指针是否指向栈或堆?

c++ - 工作函数重载如何使用可变参数进行解析?

c++ - glsl - 获取像素颜色 [像素着色器]

c++ - 如何在 Linux 上获取 Twain 数据源文件 (*.ds)

c++ - 在 C++ 中使用 getopt 时打印默认参数

c++ - 将 LLVM 添加到我的 Cmake 项目 : Why are there hardcoded paths in LLVM's Cmake file?

c++ - 为搜索优化 C++ vector

c++ - 如何包装返回 boost::optional<T> 的 C++ 函数?

c++ - 何时仅创建头文件类

c++ - Visual Studio 2010 : When creating new project vs2010 wants to open html file of wizard