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

Code walkthrough

The following code defines a function template. The keyword, template <typename T, int size>, tells the compiler that what follows is a function template:

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], input[j] );     } }}

The line, void sort ( T input[] ), defines a function named sort, which returns void and receives an input array of type T. The T type doesn't indicate any specific data type. T will be deduced at the time of instantiating the function template during compile time.  

The following code populates an integer array with some unsorted values and prints the same to the terminal:

 int a[10] = { 100, 10, ...

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