c++ - Return Generic Type data from function -
i have written following code. function func() print header , data.
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; };
is there way return data instead of print within function? if so, portion of code should modified? in advance.
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 wherther points cell<int> or cell<double> } return 0; }
i have changed question here. in main() inside loop how can check object type pointed 'it'?
thank patience , helping me :)
easiest way use 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; } }
better way use visitor pattern:
class icellvisitor; //declaration icell understand icell* pointer class icell { public: ~icell(){}; // important std::wstring header; virtual void visit( icellvisitor* v ) = 0; }; template <class t> class cell; // 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; };
now need definition of concrete visitor keep algorithm each type:
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; }