C++ Programming Guide

Function Templates

A function template describes a set of related functions that differ only by the types of their arguments or return values.

C++ 5.0 does not support non-type template parameters for function templates.

Function Template Declaration

You must declare a template before you can use it. A declaration, as in the following example, provides enough information to use the template, but not enough information to implement the template.


template <class Number> Number twice( Number original );

In this example, Number is a template parameter; it specifies the range of functions that the template describes. More specifically, Number is a template type parameter, and its use within template declarations and definitions stands for some to-be-determined type.

Function Template Definition

If you declare a template, you must also define it. A definition provides enough information to implement the template. The following example defines the template declared in the previous example.


template <class Number> Number twice( Number original )
    { return original + original; }

Because template definitions often appear in header files, a template definition might be repeated in several compilation units. All definitions, however, must be the same. This restriction is called the One-Definition Rule.

C++ 5.0 does not support non-type template parameters for function templates. For example, the following template is not supported because its argument is an expression instead of a type.


template <int count> void foo( )  // unsupported non-type parameter
{
    int x[count]
    for (int i = 0; i < count; ++i ) 
        // ... do something with x
}

foo<10>(); // call foo with template argument 10; unsupported

Function Template Use

Once declared, templates can be used like any other function. Their use consists of naming the template and providing function arguments. The compiler infers the template type arguments from the function argument types. For example, you can use the previously declared template as follows.


double twicedouble( double item )
    { return twice( item ); }