May 18, 2011

C++ Function Templates

One of the seldom used features of the C++ programming language is type parametrization a.k.a. Template. This often overlooked feature actually enables a separate programming paradigm - Generic Programming. This allows functions and classes to operate on generic data types. Functions and classes can work on many different data types without being rewritten for each type. There are two kind of templates in C++, function templates and class templates.

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