What Are Templates?

OverviewHow Do I

Templates are mechanisms for generating functions and classes based on type parameters (templates are sometimes called “parameterized types”). By using templates, you can design a single class that operates on data of many types, instead of having to create a separate class for each type.

For example, to create a type-safe function that returns the minimum of two parameters without using templates, you would have to write a set of overloaded functions like this:

// min for ints
int min( int a, int b )
    return ( a < b ) ? a : b;

// min for longs
long min( long a, long b )
    return ( a < b ) ? a : b;

// min for chars
char min( char a, char b )
    return ( a < b ) ? a : b;

//etc...

By using templates, you can reduce this duplication to a single function template:

template <class T> T min( T a, T b )
    return ( a < b ) ? a : b;

Templates can significantly reduce source code size and increase code flexibility without reducing type safety.