Описание тега function-templates

A function template behaves like a regular function except that works with types specified on the template arguments. The template arguments could be part of the function arguments and/or the function body. Each unique combination of template arguments will become an unique function when instantiated.

A function template by itself is not a type, or a function, or any other entity. No code is generated from a source file that contains only template definitions. In order for any code to appear, a template must be instantiated: the template arguments must be determined so that the compiler can generate an actual function (or class, from a class template).

Explicit instantiation

An explicit instantiation definition forces instantiation of the function or member function they refer to. It may appear in the program anywhere after the template definition, and for a given argument-list, is only allowed to appear once in the program.

An explicit instantiation declaration (an extern template) prevents implicit instantiations: the code that would otherwise cause an implicit instantiation has to use the explicit instantiation definition provided somewhere else in the program.

Implicit instantiation

When code refers to a function in context that requires the function definition to exist, and this particular function has not been explicitly instantiated, implicit instantiation occurs. The list of template arguments does not have to be supplied if it can be deduced from context

Template argument deduction

In order to instantiate a function template, every template argument must be known, but not every template argument has to be specified. When possible, the compiler will deduce the missing template arguments from the function arguments. This occurs when a function call is attempted and when an address of a function template is taken.

This mechanism makes it possible to use template operators, since there is no syntax to specify template arguments for an operator other than by re-writing it as a function call expression.

Template argument deduction takes place after the function template name-lookup (which may involve adl) and before overload-resolution.

Template argument substitution

When a template argument is specified explicitly, but does not match the type of the corresponding function argument exactly, the template argument is adjusted

Overload resolution

To compile a call to a function template, the compiler has to decide between non-template overloads, template overloads, and the specializations of the template overloads.