【发布时间】:2010-11-09 19:29:45
【问题描述】:
我偶然发现了一个问题,乍一看很容易解决,但仔细研究似乎不是。
我的程序中有项目需要处理多种类型,因此我决定以通用、可扩展的方式处理这些项目:
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;
这很好。现在我有了想要与此类分开的 GUI 组件,所以我想根据类型生成 GUI 组件:
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]);
因为 m_Items[0] 的类型是 ItemBase*。
那么我该如何解决这个问题呢?什么设计模式或模板技巧可以帮助我?
【问题讨论】:
-
您是否遇到编译时错误?运行时错误?
-
编译时“没有一个重载可以转换所有参数类型”
-
好吧,一方面,您的抽象声明不正确。抽象声明后面不应有 {}。 {} 供派生类实现。这也意味着您的 ItemT 类需要实现基类的析构函数。
-
它被称为带有身体的纯虚拟:非常罕见,但完全合法。
标签: c++ templates inheritance overloading