C++: Templates

C++ Templates are used for writing generic programming. C++ allows to define function templates and class templates.

In C++, we use template keyword to write generic programming. The syntax of the template declaration starts with

template<class T>

Where template is the keyword which indicates the particular function or class is a generic function or class. Here class keyword is not to create a class; it declares a substitution parameter (T) and that represents a type name.

The type of the variables used in templates are known at the time of using them or at the time of creating an instance of them. For example:

// Function Template
//
template<class T>
T Sum(T a, T b)
{
	return (a + b);
}

Sum is a function template takes two arguments of type unknown. The type of the arguments come to know when we use the function Sum. If we call the Sum function as

Sum(10, 20);

the arguments of type int. So, in this case Sum is a function taking two integer type arguments and returns an integer value.

Or, if we call the Sum function as

Sum(10.234, 20.435);

the arguments of type float. So, in this case Sum is taking two float values and returns a float value.

As mentioned before, C++ allows class templates as well. Like function template definition, we use template keyword to define a class template. For example:

#include <iostream>

using namespace std;

// Class Template
//
template<class T>
class MyArray
{
public:
	T m_array[100];

	T& operator[](int index)
	{
		if ( index < 0 || index >= 100 )
			throw "Out of Range";

		return m_array[index];
	}
};

// 
// 
int main()
{
	try
	{
		MyArray arr;
		arr[0] = 1234;
	
		cout << arr[0] << endl;

		MyArray arrStr;
		arrStr[0] = "Hello!";

		cout << arrStr[0] << endl;

		arrStr[100] = "World.";

		cout << arrStr[100] << endl;
	}
	catch(char *ex)
	{
		cout << "Error: " << ex << endl;
	}

	return 0;
}

MyArray is a class template, defined to hold any type of array of variables. For simplicity, this class holds up to 100 array elements at a time. The type of elements comes to know at the time of creating an instance of the class

MyArray<int> arr;

and

MyArray<char *> arrStr;

In first case, it holds array of int elements and in second case, MyArray holds an array of strings.

**

Leave a Reply