Home C++ Introduction Decisions Loops Input/Output Functions Stack and Heap References Arrays Searching and Sorting Pointers Character and Strings Structures Classes Inheritance Exceptions Templatess Recursion STL Modern C++ Misc Books ----

Templates


Contents

Function Templates



File: template1.cpp
#include <iostream>

using namespace std;


template <class T> T GetMax (T a1, T b1)
{
	T result;
	result = (a1>b1)? a1 : b1 ;
	return (result);
}

int main ()
{
	int i1=5, j1=6, k1;
	long l1=10, m1=5, n1;

	k1 = GetMax<int>(i1, j1 );
	n1 = GetMax<long>(l1, m1 );
	cout << k1 << endl;
	cout << n1 << endl;
	return 0;
}
Output:

ajay.mittal@USEUG-57MJ2J3 ~/cplus
$ ./a.exe
6
10
template T GetMax (T a1, T b1)

The above is a declaration for the function. We are stating that we can pass "T" which is a type parameter to the function "GetMax" . It is used as:

k1 = GetMax<int>(i1, j1 );
n1 = GetMax<long>(l1, m1 );

We use the syntax "<int>" to specify the type that we are passing a type. We do not have to create 2 separate functions for the different types "int" and "long" . In the above code we are explicitly stating the type for the function.
k1 = GetMax<int>(i1, j1 );
We do not need to give the type "<int>" if the compiler can figure out the type.

File: template2.cpp
#include <iostream>

using namespace std;


template <class T> T GetMax (T a1, T b1)
{
	T result;
	result = (a1>b1)? a1 : b1 ;
	return (result);
}

int main ()
{
	int i1=5, j1=6, k1;
	long l1=10, m1=5, n1;

	k1 = GetMax(i1, j1 );
	n1 = GetMax(l1, m1 );
	cout << k1 << endl;
	cout << n1 << endl;
	return 0;
}