Function templates

A class template describes an infinite set of classes, and the most common place you?ll see templates is with classes. However, C++ also supports the concept of an infinite set of functions, which is sometimes useful. The syntax is virtually identical, except that you create a function instead of a class.
The clue that you should create a function template is, as you might suspect, if you find you?re creating a number of functions that look identical except that they are dealing with different types. The classic example of a function template is a sorting function. However, a function template is useful in all sorts of places, as demonstrated in the first example that follows. The second example shows a function template used with containers and iterators.

Here?s a test program, that includes the use of the Standard Library complex number type:

Share
Tweet
Share
Pin