C++ function template
1 2 3 4 5 6 7 8 |
|
When using a template function, the compiler generates the corresponding function definition according to the actual type.
overloaded template
Not all types use the same algorithm, and template function definitions can be overloaded just like regular functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
|
Template limitations
Sometimes, the corresponding operation of type T is only applicable to arrays. If T is a structure, the template function will not be established.
Likewise, if(a>b)
if T is a structure, then > does not hold
solution:
- overloaded operators
- Provide reified template definitions for specific types
show materialization
When the compiler finds a reification definition that matches a function call, it uses that definition and does not look for a template.
- For a given function name, there can be non-template functions, template functions, and explicitly reified template functions and their respective overloaded versions.
- Shows that reified prototypes and definitions start with
template<>
and indicate the type by name - The calling order is: non-template function > materialized template function > template function
1 2 3 4 5 6 7 8 |
|
instantiation and concretization
Note: A function template does not generate a function definition, it just generates a scheme for generating a function definition. When the compiler uses a template to generate a function definition for a specific type, it gets a template instance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
Determination of template function type
1 2 3 4 5 |
|
C++11 adds decltype
keywords
1 2 3 4 5 |
|
Steps used decltype(expression) var
:
1. If expression is not enclosed in parentheses, var is of the same type as expression, including qualifiers such as const
1 2 3 4 5 6 |
|
2. If expression is a function call, var has the same type as the return value. does not actually call the function, the compiler determines the return value type by looking at the prototype
3. If expression is an lvalue, var is a reference to its type. Common situations are as follows:
1 2 3 4 5 6 |
|
4. If none of the first 3 items are satisfied, then var has the same type as expression
1 2 3 4 5 6 |
|
If declared multiple times, can be combined typedef
withdecltype
1 2 3 |
|
However, some function templates that need to define the return value type still cannot be resolved, such as:
1 2 3 4 5 |
|
C++新增语法auto h(int x,float y) -> double
,这称为后置返回类型,auto是一个占位符
1 2 3 4 5 |
|