Sun Studio 12: C++ User's Guide

6.1 Function Templates

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

6.1.1 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 the template definition stands for a type determined at the location where the template is used.

6.1.2 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.

The compiler does not support expressions involving non-type template parameters in the function parameter list, as shown in the following example.


// Expressions with non-type template parameters
// in the function parameter list are not supported
template<int I> void foo( mytype<2*I> ) { ... }
template<int I, int J> void foo( int a[I+J] ) { ... }

6.1.3 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 can infer 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 ); }

If a template argument cannot be inferred from the function argument types, it must be supplied where the function is called. For example:


template<class T> T func(); // no function arguments
int k = func<int>(); // template argument supplied explicitly