CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

C++: Templates

C++ Templates are used for writing generic programming. C++ allows defining the function templates and class templates.

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

template<class T>

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

The type of variables used in templates is 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);
}

The Sum is a function template that takes two arguments of type unknown. The type of 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 returning 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 the 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 the first case, it holds an array of int elements and in the second case, MyArray holds an array of strings.

**

C++: Templates

Leave a Reply

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

Scroll to top