【发布时间】:2016-03-02 12:50:53
【问题描述】:
我目前正在开发一个电子表格应用程序,但我遇到了模板问题。 模板的每个单元格都可以包含一个变量,该变量可以是任何标准类型。
相关类是SpreadSheet,其最重要的成员变量是SheetCells,它有
输入vector< vector<CellBase*> >。 CellBase 类是 CellField<T> 的抽象类
派生的,后者是模板类,存储一条数据正好对应一个单元格
的电子表格。
我有另一个班级SheetView,最终必须显示电子表格。 (为了简单起见,
假设这个类可以完全访问其他所有类。)这个类并不真正关心什么类型
每个单元格的值都是,因为它无论如何都会将所有内容转换为字符串。但是,我的问题是写作
SpreadSheet 的成员函数,它返回一个包含数据的字符串。我的第一个想法是写一个函数
std::string SpreadSheet::getDataFromSheet(int row, int column) SheetView 将调用,然后该函数将执行
return (std::to_string(SheetCells[row][column] -> getData())),其中getData()是CellField<T>的成员函数,返回
T 类型的东西。
但是,由于SheetCells 包含指向CellBase 类的指针,我必须使getData 成为CellBase 的成员,
但这是不可能的,因为我希望getData() 返回一个类型为T 的变量,与模板类的类型相同
CellField.
所有类定义的相关部分如下。
//SpreadSheet
class Spreadsheet
{
private:
int _height, _width;
public:
Spreadsheet(int newHeight, int newWidth);
~Spreadsheet();
string getData(int row, int column);
vector< vector<CellBase*> > SheetCells;
};
//CellBase
class CellBase
{
public:
CellBase();
virtual ~CellBase();
};
//CellField
template<typename T>
class CellField : public CellBase
{
public:
CellField(T newValue);
virtual ~CellField();
T getData();
T _value;
};
所以简而言之,我希望能够从SpreadSheet调用getData(),但是后者的成员变量
只包含指向CellBase 类的指针(但这些类实际上是CellField<T> 类型)。
我看过类似的问题,但似乎都没有解决基类成员函数调用模板class<T> 函数的问题,后者和前者需要返回T 类型的变量。也许void* 指针会起作用?
【问题讨论】:
-
许多可能的答案...我将使用虚拟纯函数“getData”,它返回一个 boost::any,它允许您存储许多不同的类型
标签: c++ templates inheritance polymorphism