c++ - Pointer to template class object -
i'm trying create individual list templated value, unfortunately can not link list listelements templates.
in main call list<int> list1;
create instance of class list. list contains multiple listelements contain value, should templated.
compiler throws error @
listelement* first; listelement* last;
in list.h. says c2955 - 'listelement' : use of class type requires type argument list
list.h
#pragma once #include <string> #include "listelement.h" template<class t> class list { private: listelement* first; listelement* last; public: list(); ~list(); void printlist(); void pushback(t value); void pushfront(t value); };
list.cpp
#include <iostream> #include "list.h" template<class t> list<t>::list() { first = null; last = null; } template<class t> list<t>::~list() { } template<class t> void list<t>::pushback(t value) { if (last) { listelement* tmp = last; last = new listelement(value); last->setprev(tmp); tmp->setnext(last); } else { first = new listelement(value); last = first; } } template<class t> void list<t>::pushfront(t value) { if (first) { listelement* tmp = first; first = new listelement(value); first->setnext(tmp); tmp->setprev(first); } else { last = new listelement(value); first = last; } } template<class t> void list<t>::printlist() { if (first) { listelement* tmp = first; while (tmp) { std::cout << tmp->getvalue() << std::endl; if (tmp != last) tmp = tmp->getnext(); else break; } } else { std::cout << "list empty!" << std::endl; } } template class list<int>; template class list<std::string>;
listelement.h
#pragma once #include <string> template<class t> class listelement { private: listelement* next; listelement* prev; t value; public: listelement(t val); ~listelement(); listelement* getnext() { return next; } listelement* getprev() { return prev; } void setnext(listelement* elem) { next = elem; } void setprev(listelement* elem) { prev = elem; } t getvalue() { return value; } };
listelement.cpp
#include "listelement.h" template<class t> listelement<t>::listelement(t val) { value = val; } template<class t> listelement<t>::~listelement() { } template class listelement<int>; template class listelement<std::string>;
listelement
template, want use specific instantiation pointers:
template<class t> class list { private: listelement<t>* first; listelement<t>* last; // note: ^^^
likewise other occurrences. within template, template name usable current instantiation, i.e., within list
, can use list
shortcut list<t>
.
Comments
Post a Comment