O'Reilly logo

Mastering C++ Programming by Jeganathan Swaminathan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Function templates

A function template lets you parameterize a data type. The reason this is referred to as generic programming is that a single template function will support many built-in and user-defined data types. A templatized function works like a C-style macro, except for the fact that the C++ compiler will type check the function when we supply an incompatible data type at the time of invoking the template function.

It will be easier to understand the template concept with a simple example, as follows:

#include <iostream>#include <algorithm>#include <iterator>using namespace std;template <typename T, int size>void sort ( T input[] ) {     for ( int i=0; i<size; ++i) {          for (int j=0; j<size; ++j) {              if ( input[i] < input[j] ) swap (input[i], ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required