C++: Templates


The concept of function overloading states that we can have two or more functions having the same name, but they should be different either in terms of the number of arguments or data types. In function overloading, we are required to give the declaration and definitions of all overloaded functions.

Template is a method of giving a single function or a single class for a group of similar functions or classes in a generic manner.

Function template

When a single function is given for a group of function in a generic manner (which can change at runtime according to the calling function) is called as function template.
In such a function at least one formal argument has to be generic.

• The main advantage of using function template is avoiding unnecessary repetition of source code.
• The object code becomes more compact then the conventional way of declaring and defining the functions.
• The generic argument in the function definition changes at runtime as per the calling function.

template<class T>
returntype functionname(list of arguments)

the template is a keyword
class is a keyword
function template starts with the keyword template and one of the arguments has to be generic.

Number Of Visitors