### Function Template Declarations and Definitions

When a template function is defined explicitly within a compilation unit , this definition is used in preference to any instantiation from the function template. For example, if one compilation unit contains the code:

    #include <iostream.h>
    template <class T> T f(T i) {return i+1;}
    void main()
    {
          cout << f(2) << endl;
    }

and another contains:

    int f(int i) {return i+2;}

when compiled and run, the program prints the number 4 to standard output, indicating that the explicitly defined function was used to resolve the call to f().

Each template, whether of a class or of a function, must be defined at most once within a compilation unit. The same applies to an explicitly defined template class or function. Function templates and class templates can be declared many times.

A template class is considered declared if its name is used. A template function is considered declared if any of the following applies:

- A function whose name matches a function template's name is declared, and an appropriate template function can be generated.
- A function whose name matches a function template's name is called, and an appropriate template function can be generated.
- A function whose name matches a function template's name is called, and the template function has been explicitly defined.
- The address of a template function is taken in such a way that instantiation can occur. This means the pointer to function must supply a return type and argument types that can be used to instantiate the template function.

A template function is instantiated or generated if the function is referenced in any of the following ways, provided that function is not explicitly defined elsewhere in the program:

- The function is declared.
- A call to the function is made.
- The address of the function is taken.

When a template function is instantiated, the body of the function template is compiled using the template argument list of the template class to instantiate the template arguments. Any errors in the function definition are flagged at this time. If a template function is never generated from a function template, it is not compiled. In this case, some errors in the function definition might not be flagged by the compiler.

Class Templates

Function Templates
Overloading Resolution for Template Functions
Explicitly Defined Template Functions
Differences between Class and Function Templates