Types of Templates in C++

Templates in C++

In C++, template is a new concept that enables us to define generic classes and functions and thus provides support for generic programming. A template can be used to create a family of classes or functions. A template can be considered as a kind of macro. When an object of a specific type is defined for actual use.

Class Templates

It is a simple process to create a generic class using a template with an anonymous type. It has the following syntax:

template
class class-name
{
.....
..... // class member specification
..... // Anonymous type T
..... // Wherever appropriate
.....
};

Function Template

Like class templates, we can also define function templates that could be used to create a family of functions with different argument types. It has the following syntax:

template
return-type function-name(arguments of type T)
{
......
...... // body of function
...... // type T
...... // wherever appropriate
......
}

 

Member Function Template

When we created a class template for vector, all the member functions were defined outside the class as well. But remember that the member functions of the template classes themselves are parameterized by the type argument (template class). It has the following syntax:

Template
return-type class-name  :: function-name(arglist)
{
......
...... // body of function
......
}