Function Templates in C++


Templates in C++:

Writing a function or a class that can work for family of functions or classes is known as generic programming. C++ supports this concept with the feature known as templates.

Function Template:

Writing a function that can work for family of functions is known as function template. At least one parameter must be of generic type (parametrized data type). Conversely, you can declare and define a function template without arguments but you will not be able to call it, since the data-type is resolved during function call.

The main advantage of using function template is to avoid unnecessary code repetition. This ultimately supports small size of byte code and compactness in the program.

Preferable only when the statements are same in multiple overloaded functions but just the data type on which they operate is different. This avoids multiple declaration and definition of the functions.

Avoid function template when the operations within the function body vary with separate business logic inside the function.

Further more, function templates can still be overloaded by creating function and/or function template with same name and different argument.

If you are asked to demonstrate a function template in University Exam or VIVA or Technical Job Interview, don’t forget to demonstrate it with the help of minimum of two data-type, only then the real power of templates surface. Nonetheless, the problem in hand must have a nature so that it is solvable using templates. Don’t invest your time and brain if the problem in hand doesn’t have such nature. The best way to identify is by analyzing whether the operations within the functions  differ that cannot be converted to a single function? If YES, don’t prefer to template them, instead, prefer using overloaded functions. This will save your time while debugging and also remain well-documented, readable program.

General syntax to declare a function template:

‘T’ here, is the parametrized data type, this variable-name is user defined, must be associated while declaration and definition.

It is also possible to declare a function template, and later define it. In such case the declaration would look like:

The definition would look like:

A simple C++ program to demonstrate the concept:

The final output would look like:


Would You Mind Sharing?


1 Trackback / Pingback

  1. Class Templates in C++ – Never Stop Learning

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.