As we already know of inheritance, it is a good way of reusing your code.
However, Visual C++ provides another way of reusing your code. We can do this
through templates. With templates you can make the 'type' parameter. Let me
explain. When you had this class that shows all processor information. The class
is huge, and it uses all integers. What if, in time, the integer wouldn't be
able to store the information of the processor (just because it's out of range
for the integer). Now you'll need to review all your code and change the
integers to longs. Or when you have this class that handles int arrays, and
someday you'll need the exact same class, only you want it to handle floats.
For these problems we have templates. Let me show you some code:
void Add(int Value);
As it becomes clear from this code, you cannot handle floats with this class.
A float class would look like this:
void Add(float Value);
Ok, we can handle this little bit of change.. but what if you had lots of
functions, and what if we needed them same class for short, char etc...
You might now the old C macros (#define), template based programming is just
like that (in a way). But, type macros aren't type safe, templates are. If you
want to know how to create a template please look at the code below:
template <typename Type>
void Add(Type Value);
That wasn't so hard? right? Now lets see how we can USE this template,
by the following code snippet:
CMyArray <int> iArray;
No, finally, we may also use the Templates as containers. Checkout the
in template based programming we would make it look like this, no matter what the brand is.
template <typename MyCar>
now, as we want to use the template.. use this code to use it!
I hope this article has helped you understand the meaning of template based programming,
but above all, how to use it and why use it.