September 2017
Beginner to intermediate
384 pages
8h 4m
English
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], ...