c++ - Generic list deleting non pointers -


i have generic list template

template<class t> class genericlist {     //the data storeed in chained list, not important.     struct c_list { t data; c_list* next; ...constructor... };  public:     bool isdelete;     genericlist() : isdelete(false) {...}      void add(t d) {         c_list* tmp = new c_list(d, first->next);         //this not important again...     }      ~genericlist() {         c_list* tmp = first;         c_list* tmp2;         while(tmp->next!=null) {             if (isdelete) { delete tmp->data; } //important part             tmp2=tmp->next;             delete tmp;             tmp=tmp2;          }     } }; 

the important part isdelete
this sample code

i need because want store data this:

genericlist<int> list; list.add(22);list.add(33); 

and also

genericlist<string*> list; list.add(new string("asd")); list.add(new string("watta")); 

the problem if store <int> compiler said cannot delete non pointer variables, don't want in case. how can solve this?
when store <int*> there no compiler error...

without changing code, solve problem as

template<class t> class genericlist  {   //same before    //add function template    template<typename t>    void delete_if_pointer(t & item) {}  //do nothing: item not pointer     template<typename t>    void delete_if_pointer(t* item) { delete item; } //delete: item pointer    ~genericlist() {        c_list* tmp = first;        c_list* tmp2;        while(tmp->next!=null) {           delete_if_pointer(tmp->data); // call function template           tmp2=tmp->next;           delete tmp;           tmp=tmp2;        }    } }; 

edit: noticed @ildjarn has provided similar solution. there 1 interesting difference: solution not require mention type of data when calling function template; compiler automatically deduces it. @ildjarn's solution, however, requires mention type explicitly; compiler cannot deduce type in solution.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -