从函数返回泛型数据
Return Generic Type data from function
我编写了以下代码。函数func()打印头文件和数据。
class ICell
{
public:
wstring header;
virtual void Fetch() = 0;
};
template <class T>
class Cell : public ICell
{
public:
//wstring header;
T data;
void Fetch()
{
wcout<< header << L": ";
cout<<data<<endl;
}
// implementation of cell methods
};
class Row
{
public:
vector <ICell *> cells;
};
是否有任何方法可以返回数据而不是在函数中打印?如果是这样,应该修改代码的哪一部分?提前谢谢。
int main()
{
Cell<int>c1;
Cell<double>c2;
c1.header = L"Roll", c1.data = 100;
c2.header = L"CGPA", c2.data = 3.5;
Row r;
r.cells.push_back(&c1);
r.cells.push_back(&c2);
vector <ICell *>::iterator it;
for(it=r.cells.begin();it!=r.cells.end();it++)
{
//checkt type of it wherther it points Cell<int> or Cell<double>
}
return 0;
}
我把问题改了一下。在main()内循环我怎么能检查对象类型是由"它"指向?
感谢大家的耐心和帮助:)
最简单的方法是使用dynamic_cast
:
vector <ICell *>::iterator it;
for(it=r.cells.begin();it!=r.cells.end();it++)
{
Cell<int>* cell_i= dynamic_cast<Cell<int>*>(*it);
if(cell_i)
{
do_something(cell_i->data);
continue;
}
Cell<double>* cell_d= dynamic_cast<Cell<double>*>(*it);
if(cell_d)
{
do_something(cell_d->data);
continue;
}
}
更好的方法是使用访问者模式:
class ICellVisitor; //declaration for ICell to understand ICell* pointer
class ICell
{ public:
~ICell(){}; // important
std::wstring header;
virtual void visit( ICellVisitor* v ) = 0;
};
template <class T> class Cell; // for Cell<T>* pointer
class ICellVisitor
{ public:
virtual void visit( Cell<int>* c ) = 0;
virtual void visit( Cell<double>* c ) = 0;
virtual void visit( Cell<float>* c ) = 0;
virtual void visit( Cell<long long>* c ) = 0;
};
template <class T> class Cell : public ICell
{ public:
//wstring header;
T data;
void visit( ICellVisitor* v )
{
std::wcout<< header << L": ";
v->visit(this);
}
// implementation of cell methods
};
class Row
{ public:
std::vector <ICell *> cells;
};
现在我们需要定义具体的访问者来保持每种类型的算法:
class MyCellVisitor: public ICellVisitor
{ public:
void visit( Cell<int>* c ){
std::wcout<<"(int)"<<c->data<<std::endl;
}
void visit( Cell<double>* c ){
std::wcout<<"(double)"<<c->data<<std::endl;
}
void visit( Cell<float>* c ){
std::wcout<<"(float)"<<c->data<<std::endl;
}
void visit( Cell<long long>* c ){
std::wcout<<"(long long)"<<c->data<<std::endl;
}
};
int main()
{
Cell<int>c1;
Cell<double>c2;
c1.header = L"Roll", c1.data = 100;
c2.header = L"CGPA", c2.data = 3.5;
Row r;
r.cells.push_back(&c1);
r.cells.push_back(&c2);
MyCellVisitor visitor;
std::vector <ICell *>::iterator it;
for(it=r.cells.begin();it!=r.cells.end();it++)
{
(*it)->visit( &visitor );
}
return 0;
}
相关文章:
- 错误处理.将系统错误代码映射到泛型
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 链表的泛型函数remove()与成员函数remove)
- 给定一个类型,如何派生一个泛型更广泛的类型(例如,用于溢出安全求和)?
- 模板化接口 - 创建一个泛型模板类以返回任何容器
- 如何编写将要继承的泛型代码?
- C++17 如何保存泛型可调用对象以供以后使用
- 使用宏扩展的泛型:为什么指令缓存使用不当?
- C++泛型类错误,问题出在哪里?
- C++泛型类,单独实现?
- 将参数传递给泛型 lambda 时复制构造函数不正确
- 泛型枚举和其他类型的重载模板函数
- 使用泛型类型推送到堆栈时出现问题
- 使用泛型编程的基本数据结构
- 如果我们不想要模板/泛型中的任何数据类型怎么办
- 使用泛型资源库设置数据成员
- 从函数返回泛型数据
- 为泛型数据类型创建自己的迭代器
- 尝试用c++类创建泛型数据类型的问题
- 数据映射:从"any"类到泛型键值映射(C++)