5 Useful C++ Template functions implimentations


Generic Programming can save a lot of time and code lines. These snippets are some basic implimentations of template functions in C++ such as sorting, printing, finding maximum, minimum.


Introduction


Template functions is an example of generic programming and is a very useful feature in C++. Many times there comes a situation when you write a function for int datatype like finding maximum of two integers. This works for integer variables but when it comes to float or double variables, you realize you will have to write the function for this datatype all over again.

int findMax(int a, int b){

if(a>b)

return a;

else

return b;

}

float findMax(float a, float b){

if(a>b)

return a;

else

return b;

}

If you compare the two codes, you feel a sense of redundancy. Functions for both the datatypes are almost same. The only difference being usage of datatype declarations. In C++ there is a way to generalize this.


Template Functions


Template functions introduce a way to treat datatypes as variables. The syntax is as follows :

template <typename T1, typename T2,...>

T1 functionName(T1 a, T2 b, ...){

.....

}


Example 1


This function will calculate maximum for any two variables.

template <typename T1>

T1 findMax(T1 a, T1 b){

if(a>b)

return a;

else

return b;

}


Example 2


This function prints an array of any datatype with its length given as an input argument.

template <typename T1>

T1 printArray(T1 arr[], int length){

cout << "The array is : \n";

for(int i=0; i<length; i++)

cout << arr[i] << endl;

}


Example 3


This function will copy elements array2 to array1. This is a common task when writing codes in C++.

template <typename T1>

T1 copyArray(T1 array1[], T1 array2[], int length){

for(int i=0; i<length; i++)

array1[i] = array2[i];

}

Rohan Raja

Recently graduated, majoring in Mathematics and Computing from IIT Kharagpur, Rohan is a technology enthusiast and passionate programmer. Likes to apply Mathematics and Artificial Intelligence to devise creative solutions to common problems.