c++ - Getting template error -


this question has answer here:

i getting compilation error , please not able resolve

 class {         public :         a() {}          virtual ~a() {}          int getid() { return m_id; }         void setid(int id) { m_id = id ; }          private:         int m_id ;     };           class b : public {      };       class c: public {      };      template<class t>     t* returnobject(vector<t*>& vec, int id)     {         for(vector<t*>::iterator itr =vec.begin();  itr != vec.end() ; ++itr)         {             if(id == (*itr)->getid()) return (*itr);         }         return null;     }      int main()      {         vector<b*> b1;         vector<c*> c1;          b *b = new b();         b->setid(10);         b1.push_back(b);         b = new b();         b->setid(20);         b1.push_back(b);         b = new b();         b->setid(30);         b1.push_back(b);          c *c = new c();         c->setid(6);         c1.push_back(c);         c = new c();         c->setid(12);         c1.push_back(c);         c = new c();         c->setid(18);         c1.push_back(c);          b *bcd = returnobject<b>(b1,30);          cout<< bcd <<endl ;          return 0;     } 

i getting compilation error

castex.cpp: in function `t* returnobject(std::vector<t*, std::allocator<t*> >&, int)': castex.cpp:29: error: expected `;' before "itr" castex.cpp:29: error: `itr' not declared in scope castex.cpp: in function `t* returnobject(std::vector<t*, std::allocator<t*> >&, int) [with t = b]': castex.cpp:61:   instantiated here castex.cpp:29: error: dependent-name ` std::vector<t*,std::allocator<t*> >::iterator' parsed non-type, instantiation yields type 

the problem vector<t*>::iterator depends on template parameter. compiler doesn't know every single std::vector specialization has iterator member type, need explicitly state is type:

for(typename vector<t*>::iterator itr =vec.begin();  itr != vec.end() ; ++itr) //  ^^^^^^^^ 

see this question more information typename.

of course, sidestep whole issue in c++11 , use auto:

for(auto itr =vec.begin();  itr != vec.end() ; ++itr) 

or range-based loops:

for (auto&& element : vec) 

or std::find_if:

std::find_if(std::begin(vec), std::end(vec),              [id](auto&& el){ return id == el->getid() }); 

although std::find_if returns std::end(vec) if element not found, rather null.


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -