代码之家  ›  专栏  ›  技术社区  ›  DanDan

当所有类型都未知时从基类重载函数

  •  1
  • DanDan  · 技术社区  · 14 年前

    我的程序中有需要处理多种类型的项,因此我决定以通用、可扩展的方式处理这些项:

    class ItemBase
    {
    public:
     virtual ~ItemBase() = 0 {}
        // pure virtual class, some extra members
    };
    
    template<typename T>
    class ItemT : public ItemBase
    {
    public:
     ItemT(const T &data) : m_Data(data) {}
    
     T m_Data;
    };
    

    我现在可以在集合中存储任何类型:

    std::vector<ItemBase*> items;
    

    GuiComponent* BuildComponent(ItemT<int> &item)
    {
        // do whatever based on this type, the int is needed
    }
    
    GuiComponent* BuildComponent(ItemT<double> &item)
    {
        // do whatever based on this type, the double is needed
    }
    

    这几乎是美丽的编码。不幸的是它不起作用。如本程序所示:

    std::vector<ItemBase*> m_Items;
    m_Items.push_back(new ItemT<int>(3));
    m_Items.push_back(new ItemT<double>(2.0));
    BuildComponent(*m_Items[0]);
    

    那么我该如何解决这个问题呢?什么样的设计模式或模板技巧能帮到我?

    1 回复  |  直到 14 年前
        1
  •  4
  •   icecrime    14 年前

    简单的答案是:添加一个虚拟 buildComponent 方法 ItemBase . 但是,由于您希望将GUI组件分开,我建议您 Visitor

    一个非常简单的实现将包括:

    • accept(AbstractVisitorType &) 虚拟方法
    • 通过调用 visitor.visit(*this) ,这意味着 AbstractVisitorType 必须提供虚拟 visit
    • 提供此访问者的具体实现,它将在其每个 参观

    但是请注意,Visitor模式只适用于一个相当稳定的类层次结构:使用ItemT模板的新实例化将需要在Visitor端进行维护来处理这个新类型(但是您最初的想法也有同样的问题)。

    现代C++设计(Andrei Alexandrescu)第10章是关于访问者模式的一个伟大的阅读。