Function Templates in C++

Template is a method of writing a single function or class for a family of similar functions or classes in a generic manner. When a single function is written for a family of similar functions, it is called as ‘function template’. In such function at least one formal argument is generic.

In function overloading, though the same name is used for all functions which are defined as overloading, yet the codes are yet to be repeated for every function. Only the function names are same, but the function definition and declaration are repeated.

swap(char *, char *) //swapping two integer quantities
{
-----------------
------------------
}
swap(int, int) //swapping two integer quantities
{
-----------------
------------------
}
swap(float, float) //swapping two floating point numbers
{
------------------
------------------
}

C++ provides certain features with the capability to define a single function for a group of similar functions. When a function is written for a family of similar functions, they are called as function templates. The main advantage of using function template is avoiding unnecessary repetition of the source code.

The object code becomes more compact than the convectional way of declaring and defining the functions. Secondly, full data type checking is carried out. The function template does not specify the actual data type of the arguments that a function accepts but it uses a generic or parameterized data type. In a function template at least one formal argument is generic.

The general syntax for declaring a function template in C++ is,

template<class T> T function_name(T formal arguments)
{
_________________________
_________________________
return(T);
}

where the template and class are keywords in C++ and the function template must start with template and the T is a parametrized data type.

The above declaration of the function template may be written in the following format also.

template<class T>
T function_name(T formal arguments)
{
---------------
---------------
return(T);
}

You might be anxious to know how the argument type is determined. The return type of the function is never considered for the actual parametrized data types to be processed. The actual data type of the function matches with the formal arguments of the function declaration whenever parameterized arguments are inferred in the function template.