Function Templates

Function Templates

When getting down to the brass tacks of good software engineering practices and design, “Function Templates” play a key role in effectively¬†working with code in an object oriented environment.

Function templates are special functions that work with any type of object to perform a common action. This allows the software engineer to create a function template whose functionality/logic can be serve more than one class type.

The format for declaring function templates are:

template <class customClassName> function_name;

OR

template <typename customClassName> function_name;

 

An example in C++ is given below:


// function template
#include <iostream>
using namespace std;

template <class T>
T GetProduct (T a, T b)
{
T result;
result = a*b;
return (result);
}

int main ()
{
int i=3, j=7, k;
long l=15, m=2, n;
k=GetProduct<int>(i,j);
n=GetProduct<long>(l,m);
cout << "Product of i and j " << k << endl;
cout << "Product of l and m " << n << endl;
return 0;
}

 

 

//////////////////

//Additional example in Objective-C and CSharp will be posted soon///

/////////////////

Leave a Reply

Your email address will not be published. Required fields are marked *