C ++:模板类的向量 [英] C++ : Vector of template class
问题描述
我有一个名为Cell的模板类,如下所示:-
I have a template class named Cell as follows:-
template<class T>class Cell
{
string header, T data;
}
现在我想要另一个名为Row的类。 Row将有一个名为Cells的向量,这样我就可以向该向量添加Cell和Cell类型元素。
Now I want another class Named Row. Row will have a vector named Cells such that I can add both Cell and Cell type elements to that vector. Is it possible?
如果可以,我该怎么做?
预先感谢。
If so, how can I do that? Thanks in advance.
推荐答案
使用您提供的额外详细信息,前两个答案将无效。您需要的是一种称为单元格变体的类型,然后可以得到这些变量的向量。例如:-
With the extra detail you've provided, the first two answers won't work. What you require is a type known as a variant for the cell and then you can have a vector of those. For example:-
enum CellType
{
Int,
Float,
// etc
};
class Cell
{
CellType type;
union
{
int i;
float f;
// etc
};
};
class Vector
{
vector <Cell> cells;
};
但是,添加新类型很麻烦,因为它需要大量代码来维护。另一种选择可以使用具有通用基类的单元格模板:-
This, however, is a pain to add new types to as it requires a lot of code to maintain. An alternative could use the cell template with a common base class:-
class ICell
{
// list of cell methods
};
template <class T>
class Cell : public ICell
{
T data;
// implementation of cell methods
};
class Vector
{
vector <ICell *> cells;
};
这可能会更好,因为最初需要更新的代码较少,无法添加新的单元格类型在单元格向量中使用指针类型。如果按值 vector< ICell>
存储单元格,则由于对象切片。
This might work better as you have less code initially to update to add a new cell type but you have to use a pointer type in the cells vector. If you stored the cell by value, vector <ICell>
, then you will lose data due to object slicing.
这篇关于C ++:模板类的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!