Templates provide a way to reuse source code. Here they differ from inheritance and composition which provide ways to reuse object code. This also implies that using templates will cost more time in compilation. However, unless the template is a very complex one, the additional time in compiling is negligible.
A function template for finding maximum of two instances of the same type can be coded as following :
template <typename T>
T& max(T& x, T& y)
{
if(y < x)
return x;
return y;
}
This template function can be used for native data types as well as classes provided that the "<" operator has been overloaded for that class. The compiler will replace the T in template code with appropriate types during compilation.
If a template function is required to behave in a certain way for a certain data type, it can be specialized for those data types.
One important point about template functions is that, when working in multiple-file projects, the declaration and definition has to be in the same file.
No comments:
Post a Comment