# very easy templates tutorial?

## Recommended Posts

some time ago I asked a question about 2 linked lists and how I could use the functions (which are the same for both linked lists) for both lists. Some of you answered I should use templates and now I tried but failed. Can someone show me a very small example or give me the link to a very simple tutorial about them? I know I could also use the std::list (or something similar) but I see this as the opportunity to become familiar with this template stuff...

##### Share on other sites
write the class using the data type T with the template declaration before it

template< class T >struct ListNode{     ListNode<T> * next;     ListNode<T> * prev;     T             data;};template < class T >class List {    T GetFrontData() { return head->data; }    T GetBackData()  { return tail->data; }private:    ListNode<T> * head;    ListNode<T> * tail;    };

then just fill in the T when instanciate the class and if youve writin it correctly it should work.

T t;
t = t * 6; UH OH CAN T BE MULTIPLIED !!!!!

##### Share on other sites
thx, that looks like a small example :)
I think I need to make a very small console test program to play around with it for a while and get familiar until I try to implement this into my stuff...

##### Share on other sites
Here's a quick little tutorial on templates. It is fairly useful, but you are right about playing around with it first. Templates can be the devil!

- Drew

##### Share on other sites
Quote:
 Original post by Drew_BentonHere's a quick little tutorial on templates. It is fairly useful, but you are right about playing around with it first. Templates can be the devil!- Drew

Thanks for the word of warning... I read through your devil-thread and now I'm asking myself: wtf is a xpp or tpp file? Is it just a file which you include but you call it tpp because you have all the templates in it?

##### Share on other sites
Oh yea, it's just a another name for a file. Like it is just a common practice to use .cpp and .h and .c for your files. You can use like: #include "myheader.abc" - the compiler doesn't care what it's called, just wether or not it can find it.

As for your source files, they work in a similar way. However, in most IDEs like VS, .cpp is automatically compiled, so if you use something else, you will have to make sure it is compiled as a source file. Like if you add a .txt, it will not be compiled as a source file.

Take a look at another old (and dumb) post of mine to see a good use for using alternative names [smile]

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628350
• Total Posts
2982211

• 10
• 9
• 24
• 11
• 9