This documentation is archived and is not being maintained.

What Are Templates?

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 or function 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:

// what_are_templates1.cpp

// 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;

}

int main()

{

}

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

// what_are_templates2.cpp
template <class T> T min( T a, T b )
{
   return ( a < b ) ? a : b;
}

int main()
{
}

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

See Also

Templates

Show: