我有一个名为 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
,那么您将由于 对象切片而丢失数据.
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++:模板类的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!