top of page

Templates

Many times, the algorithms and functions look similar for different data types. e.g. Algorithm for sorting an array using quick sort is same whether you use string array or integer array.  Writing different classes or functions in such cases is redundant.

 

Templates provide a way to write such generic classes and function. The user can specify the concrete data type of these operations should work on.

 

Templates are type independent patterns that can work with multiple data types.

 

In C++, you can write function templates and class templates.

 

Function templates

 

A function template is a generic function which can be instantiated for different data types. 
          
To write a template function you use template header followed by function header and function body. Template header starts with keyword template and keyword class followed by an identifier enclosed in angle brackets.

 

The return type, and/or parameter types may be of template type.   The function may have non-template return types or parameters also.

Syntax :
 

template <class T>

T fn-name(para-list)

{

/*code*/

}

 

Here T  is the place holder for data type and is called template parameter. 

Let us look at an example.

In the example above, instead of return type of function, template parameter T is used. And 3 parameters to function are also of type  T
 

When this function is called with some data type - say int, compiler generates the function with that data type. - a function which takes 3 int parameters and returns an integer.

Let us look at another example where a template sum of array function is written.

Here the function is called for integer array and float array. So T gets replaced by int in first call and float in second call.

There can be more than one template parameter.


template <class T,class V>
T sumOfNumbers(T num1,V num2)
{
     T ans= num1+num2;
     return ans;
}

Template function can be used with user defined data types like structures, classes also, provided these types define all the operations used in the function.

e.g. if a class Number has written overloaded operator ">", then argument to maximum template function explained earlier can be object of Number class.

Class Template

Class templates are generic classes from which users can create classes for any data type. Normally template classes are used for containers like vector, stack etc. C++ library STL (standard template library) contain many utility template classes.

Syntax :

template <class T>

class cls-name

{

/**code**/

};

Let us look at a template for array class where type of array element is a template parameter.

Like function template, we start with the line "template <class T>"  and the dynamic array data is of type T.

Another interesting point is that for each of the function definitions of the template, we have to specify template header.

And yet one more point to remember is We have to write class declaration and definition of such class templates in a single file.

Instantiating class templates

In function templates, the instantiation did not require explicit data-type. Instead template was instantiated with the type of argument. But in case of class templates, we have to explicitly mention the data type for instantiation.

e.g.

      Array<int> iarr(10);

The line would create an Array class for integers and then create an object of this class iarr.

Let us create two objects of the Array class and call print() method on them.

Template specialization:
 

Some data types  require a different implementation than all others. e.g. A string class may need a different implementation.

 

In such cases, you can provide a different definition of template class or function for a particular data type.

Normally larger() function uses > to compare two values. But in case of C-style strings, we can not use >, instead we have to use strcmp() function. So we wrote a template specialization for c-strings.

Let us look at an example of template specialization for class templates.

We have written a 1 byte number class using char data type as specialized class. If we create object of char, this special template is used. For other types, the original template class is used for instantiation.

What is class T?

Class T stands for class name identifier. Remember that we can use classes too instead of PODs for template instantiation. In fact, we can use typename T instead of class T

template <typename T>

T max(T n1,T n2)

{

/****/

}

Default type for templates

Like functions with default values for parameters, a template can have default data type for template parameter.

template <class T=float> 

class FOO

{

    T num;

    /*****/

};

If we create an object of FOO class as shown below,

  

        FOO obj1;

     FOO<int> obj2;

then FOO class will be instantiated using float type and obj1 is created using this class. But FOO<int> will instantiate the template class using given data type viz int.

Non-template parameters in templates

A template header can have non-template parameters also similar to a function parameter. But this parameter must be integer type or pointer type. And argument provided for such parameter must be a value which is known at compile time.

e.g.

Here size is non-template parameter. We are providing integer literal values for this parameter - 5 and 3.

bottom of page