我的程序中有需要处理多种类型的项,因此我决定以通用、可扩展的方式处理这些项:
class ItemBase
{
public:
virtual ~ItemBase() = 0 {}
};
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]);
那么我该如何解决这个问题呢?什么样的设计模式或模板技巧能帮到我?