CPP templates acts as a support for generic programming technique, where parameters in algorithms are of generic types and thus can work for a variety of data types. This feature in CPP is used to define the generic classes and generic functions.

Types of CPP Templates:

Function Templates:

In function templates, templates for a function is defined.

Syntax:

template < class Ttype> ret_type func_name(parameter_list)

{

// code to be executed

}

Ttype:

This parameter is used to represent a placeholder name, to be replaced by the compiler, for a data type, within the function definition.

class:

This keyword is used before Ttype to specify a generic type in a template declaration.

Syntax: Function Templates with Multiple Parameters:

template <class T1, class T2,…..>

return_type function_name (arguments of type T1, T2….)

{

// code to be executed

}

Important points:

Function template is used by generic functions to define a set of operations that can be applied to the various types of data.

The generic functions can be overloaded by overloading the template functions (can differ in the parameter list).

For all the versions of a function, a generic function executes the same operation for the same data type.