Template Typedef how to?
Ok I have a header file that was given to us by the instructor. He told us to make it a template and then make a little prog to test it....
He uses a "typedef" to define the element type that is passed through the prog, how to I make it into a template so that it will change from "int" to "Float" what ever I want to pass through this prog.
here is the Templated Header file as I have it right now...
the error I get is this
// TEMPLATE LIST HEADER FILE
const int CAPACITY = 100;
template <class T> T ElementType; //I know this doesnt work
//typedef std::map<std::string, T> ElementType; I found this on a web page
// but I cant figure out how they use it to get around templating a typedef
template <class T> class List
List(); // def constructor
List(const List &l); // copy constructor
// public member functions
int get_size() const; // returns logical size of array
List &operator = (const List &l); // assign arrays
ElementType &operator(int index);
// returns element index of array can extract ith element and
// assign ith element. Index must be valid
bool append(const ElementType &tem);
// Appends element to end returns true if successful
// otherwise false
bool insert(const ElementType &item, int pos);
// inserts item at pos, if pos is valid. returns true if LIst is
// not full and pos is valid, otherwise false
bool erase(int pos);
// if pos >= 0 and pos < current_size item as position pos
// is removed from the array.
bool empty() const;
// tests to see if List is empty
void traverse(void process(const ElementType & item));
// discussed in class
I believe that is sayig I cant template a typedef, If I am wrong pls tell me how to make this statement work..I believe that this is all that is holding my prog from working and I cannot find anything in the book as it is pretty worthless (so says my proffessor)...
In file included from List.cpp:2:
List.h:6: error: template declaration of `T ElementType'
Thanks in advance
Just place the typedef within the class declaration.
Then List<int>::ElementType will be a typedef for int.
template<class T> class List
typedef T ElementType;
// rest of stuff
One comment, related to use of templates but not the question you've asked. One other little characteristic of template classes is that (unless you use compiler specific hacks) it is necessary to include the definitions (i.e. the bodies) of the member function within the header files. Separate compilation works differently with templates.
The typedef definition is ok. But you are placing it in the wrong spot.
Outside of the template definition, T is not declared. The compiler doesn't know what it is. You have to place it inside the templated class at a point where it is declared before it is being used (typically these typedefs come at the top of the class:
template <class T> class List
private: // or protected?
typedef std::map<std::string, T> ElementType;
/* ... The rest of your class definition ... */