Neither is better. They are different.
Templates provide a way of parametrising functions and classes at compile time. Consider the following contrived example:
1 2 3 4
|
int add(int m, int n)
{
return m + n;
}
|
Clearly, this works for floats, doubles, long doubles, unsigned intgerers, short integers, etc. So do we write the function out for each one. Of course not - it would take hours. We use template instead:
1 2 3 4 5
|
template <class T>
T add(T m, T n)
{
return m + n;
}
|
We we can say add<int>(3, 5) or add<float>(1.0f, 5.0f). They are two different functions as far as the linker is concerned, but the compiler has autogenerated them from a single template function.
Note that by something called "template argument deduction", you can in fact just write add(3, 5) or add(1.0f, 5.0f). In the first case, the compiler knows that 3 and 5 are integers so in the first case it calls add<int>(). In the second case, it knows that 1.0f and 5.0f are floats, so it calls add<float>().
We can go a step further and let the function add two variables of different types, but that involves the C++0x
decltype
keyword, so I shan't go in to that.
You can do a similar thing with classes, but there is no template argument deduction for classes.