Polymorphism and templates are easy to understand once you realise that they are really just the same as functions.
You want to use a function when you are doing the same process with different data. For example, suppose you know how to calculate the square root of two. And you know how to calculate the square root of three, and you know how to calculate the square root of four, ... You are doing the same process (calculating square roots) on different data (2, 3, 4, ...) So you make a function that looks like this:
Code:
double sqrt(int n);
You have a function called sqrt that takes a parameter called n. N can be an integer you like, and the square root of n will be returned by the function.
Now, when making complex data types, we find the same situation on a different level. In one program, you might want to store integers in a linked list. So (in C) you would make a data type called linked_list_integer. In another program, you might want to store strings in a linked list, so you would make a data type called linked_list_string. See the pattern here is the same as before. We know what a linked list is, and it seems pointless to have to make a different linked list each time we want to store a different data type in the list. So what we use (in C++) is a template. A template is like a function, but instead of having a parameter that is an integer or a float or a string, the parameter is a data type. So our template for a linked list would look like this:
Code:
template <class t>
class linked_list
{
... code that implements a linked list, using the parameter t as the data type stored in the list ...
}
And now, just like we could use the sqrt function to calculate the square root of 5 by calling sqrt(5), we can use the linked list template to create a linked list of integers by calling linked_list<int>. We can create a linked list of floats in the same way by calling linked_list<float>.
Angled brackets are used for template parameters to make them look different to function parameters, to avoid confusion.
So the linked_list class is an example of a template because it has a template parameter t. We say that the linked list class is polymorphic in the type of data that it can hold.
This website provides a very good introduction to templates, and some code examples along the lines of what I have been describing.
Good luck with your coding, kisna and justin1993.
Bookmarks
Algorithms and Data Structures
Java tutorials
Algorithms Forum