How to create function templates in C++ Programming3 min read

A function template is a function which contains generic code to operate on different types of data. This enables a programmer to write functions without having to specify the exact type of parameters. Syntax for defining a template function is as follows:

As shown above, the syntax starts with the keyword template followed by a list of template type arguments or also called generic arguments.

The template keyword tells the compiler that what follows is a template. Here, class is a keyword and Type is the name of generic argument.

Following program demonstrates a template function or function template:

Output for the above program is as follows:

In the above program compiler generates two copies of the above function template. One for int type arguments and the other for float type arguments. The function template can be invoked implicitly by writing summ(val1, val2) or explicitly by writing summ<int>(val1, val2).

Guidelines for Using Template Functions

While using template functions, programmer must take care of the following:

Generic Data Types

Every template data type (or generic data type) should be used as types in the function template definition as type of parameters. If not used, it will result in an error. Consider the following example which leads to an error:

Also using some of the template data types is also wrong. Consider the following example which leads to an error:

Overloading Function Templates

As normal functions can be overloaded, template functions can also be overloaded. They will have the same name but different number of or type of parameters. Consider the following example which demonstrates template function overloading:

Output for the above program is as follows:

Whenever a compiler encounters the call to a overloaded function, first it checks if there is any normal function which matches and invokes it. Otherwise, it checks if there is any template function which matches and invokes it. If no function matches, error will be generated.

From the above example you can see that for the call summ(a, b), normal function is invoked and for the call summ(p, q), template function is invoked.

Take your time to comment on this article.

Leave a Comment