Hey everyone!

Today I learned a really great special functions that I did not know about before – templates.

Basically, all it does lets you to define other functions with arguments, but those arguments can be of any different type. Thus, we do not have to overload functions just because they have to accept different data types. I really like this because I don’t really like to overload functions too much. It’s might not be easy to understand what I mean without an example so here it is:

for example we have function:

void findLargerNumber (int a, int b)
{
if (a == b)
cout << a << ” = ” << b << endl;
else
{
int i = a > b;
if (i)
cout << a << endl;
else
cout << b << endl;
}
}

if our arguments are doubles (or any other variable type) and we will need to perform same calculations we will need to overload findLargerNumber function with arguments for double… and for float and for long long… That could be a real pain!… It is inefficient and takes a lot of time to do… unless we use templates which will allow us to code function only once.

Here is an example:

template <class AnyType>
void findLargerNumber (const AnyType &a, const AnyType & b)
{
if (a == b)
cout << a << ” = ” << b << endl;
else
{
int i = a > b;
if (i)
cout << a << endl;
else
cout << b << endl;
}
}

all we do is: before our function findLargerNumber we add

template <class AnyType>

which called template prefix

and we change argument types to AnyType which will be out type parameter. And that is all.

Here is the program with a little main:

#include <iostream>
using namespace std;

template <class AnyType>

void findLargerNumber (const AnyType &a, const AnyType & b)
{
if (a == b)
cout << a << ” = ” << b << endl;
else
{
int i = a > b;
if (i)
cout << a << endl;
else
cout << b << endl;
}
}

int main()
{
findLargerNumber(3, 8);
findLargerNumber(5, 2);
findLargerNumber(5, 5);
findLargerNumber(3.5, 8.2);
findLargerNumber(13.0, 8.6);
findLargerNumber(‘A’, ‘a’);
return 0;
}

Isn’t cool? And notice that we do not have to write any extra code in main to call template function. So, in summary, it saves a lot of time. It can also be used with classes, but that one should be explained by Fardad in class some time later πŸ˜‰