Function template function template (C ++ primer-10)

Source: Internet
Author: User

10 function templates

10.1 function template Definition

template <typename A, typename B, int size> A Func(const B(&rArray)[size]) { return A();}

> The keyword "template" is followed by a template parameter table 'template parameter list' separated by commas (,), which can be included. The template parameter list cannot be blank. (this can be used for special purposes );

Template parameters can be template type parameter, which represents a type, or template nontype parameter, which represents a constant expression;

In general, typename in angle brackets represents the C ++ built-in data type, and class represents the C ++ data type (custom );

Template <class type, int size> type min (const type (& rarray) [size]) // size is part of the parameter, the compiler checks whether the length of the real parameter matches {type minval = rarray [0]; for (INT I = 0; I <size; I ++) {If (rarray [I] <minval) minval = rarray [I];} return minval;} // --- const int size = 5; int iarray [size] = {5, 7, 3, 22, 99}; cout <min (iarray) <Endl;

> The replacement of type and value is called template instantiation;

Template type parameters are treated as a type identifier in the same way as built-in or user-defined types. e.g. Declare variables and force type conversion;
The non-type parameter of the template is used as a constant value. The e.g. array size, initial value of the enumerated constant;

NoteIfTemplate parametersThe global name is hidden for an object of the same name, function, or type;
The object or type declared in the function template definition cannot be the same as the template parameter; (invalid or error );

The template type parameter name can be used to specify the return value of the function template. The template parameter name can only be used once in the same template parameter table, however, the template parameter names can be reused between multiple function template declarations or definitions. The template parameters used by one template definition and multiple declarations do not need to be the same; there is no limit on the number of times template parameters appear in the function parameter table. A keyword class or typename must exist before each template type parameter;

In the function template parameter table, typename and class have the same meaning. They can be used to declare parameters of different template types in the template parameter table. <design and evolution of c ++>

NoteTo enable the compiler to analyze template definitions, you must instruct the Compiler which expressions are type expressions: typename;

Template <class parm, Class U> parm minus (parm * array, U value) {typename parm: name * P; // pointer declaration parm: name * P; // The Compiler does not know whether this is a pointer declaration or multiplication}

NoteWhen the function template is declared as inline or extern, the indicator is placed behind the template parameter table, not before the keyword template;

10.2 function template instantiation

The function template specifies the actual type or value to construct an independent function: the template instantiates the template instantiation;

This process occurs implicitly and can be considered as a function.Number template called or the address of the function TemplateSide effects;

int (*pf)(int (&)[10]) = &min;// min(int(&)[10]);

The compiler checks the type of the function arguments provided in the function call. The process of using the type of the function arguments to determine the type and value of the template arguments is called the template arguments deduction template argument deduction;

NoteWhen getting the address of the function template instance, you must use the context as the template real parameter to determine a unique type or value;

typedef int (&rai)[10];typedef double (&rad)[20];void func( int (*)(rai) ){}void func( double (*)(rad) ){}//---func(&min);//error, overload-function

> Compilation error: If func () is overloaded, the compiler cannot determine the unique type of the type or the unique value of size. If func () is called, the function cannot be instantiated;

10.3 real-time deduction of template parameters

When a function template is called, the check of the function real parameter type determines the type and value of the template real parameter. This process is called the template real parameter deduction template argument deduction;

> The real parameter of the function must be the left value of an array type. The pval here is the function parameter, so it is converted to a pointer variable, which does not match the left Value Type of the array; (When passing the parameter, the group-> pointer match, pointer-> array does not work)

Template <class type, int size> type min (type (& r_array) [size]) {/*... */} void F (INT pval [9]) {// error: type (&) []! = Int * // int jval = min (pval );}

During Real-Time Parameter deduction in the template, the real-time parameter type of the function does not have to match the type of the function parameter strictly;
Allowed type conversion: conversion from left to limited to a base class;

Conversion from left to right includes conversion from left to right, conversion from array to pointer, and conversion from function to pointer;

Common Algorithm for real-parameter deduction of function templates:
1) Check the real parameters of each function in sequence to determine the template parameters that appear in the type of the real parameters of each function;
2) Find the template parameters, and deduct the corresponding template parameters by checking the type of the function arguments;
3) function parameter types and real parameter types can be converted:-left value conversion-qualified modifier conversion-conversion from a derived class to a base class;
4) if the same template parameter is found among multiple function parameters, the template parameters pushed from each of the corresponding function parameters must be the same (the template parameters will be bound to the first type)


10.4 display template parameters

Show specified explicitly specifyTemplate parameters;

E.g. func <usigned int> (1024); // 1024 is converted to the unsigned int type by the ordered standard;

When the real parameters in the function template are displayed as indicated, any implicit type conversion can be applied to convert the real parameters into the corresponding types of function parameters;

Explicit and special explicit it specification, only real parameters at the end can be omitted;

Char ch; unsigned int UI; Template <class T1, class T2, class T3> T1 sum (T2, T3); typedef unsigned int ui_type; ui_type loc1 = sum (CH, UI); // error, T1 cannot be deduced ui_type loc2 = sum <ui_type, Char, ui_type> (CH, UI); // okui_type loc3 = sum <ui_type, char> (CH, UI); // okui_type (* PF) (char, ui_type) = & sum <ui_type>; // okui_type loc4 = sum <ui_type ,, ui_type> (CH, UI); // error, only real parameters at the end can be omitted

> For the real parameters of the function pointer type of the overload function, explicitly specify them to avoid ambiguity;

Template <class T1, class T2, class T3> T1 sum (t2 OP1, T3 OP2 ){/*... */} void manipulate (INT (* PF) (INT, char); void manipulate (double (* PF) (float, float); int main () {manipulate (& sum); // error: 2yi manipulate (& sum <double, float, float>); // call: void manipulate (double (* PF) (float, float ));}

We recommend that you save the real parameters of a slightly typed template when possible to make function functions more generalized;

NoteThe return value cannot be deduced. The deduction only applies to parameters. If the return value is the same as the parameter, it can be indirectly deduced;


10.5 template compilation Mode

C ++ template compilation mode template compilation ModelSpecifies the requirements for the organization of the program defining and using the template;
Compilation mode: includes the projection model and the separation mode separation model;

10.5.1 contains the compilation Mode

The template definition is in the header file, and the template definition is included before the template instance;

Disadvantage: the implementation details are described in the mode template body, which we want to hide from users;
When the function template is very defined, the details in the header file become unacceptable;
Compile the same function template definition between multiple head files to increase the Compilation Time;
10.5.2 separate compilation Mode

The function template is declared in the header file;

// Model2.h // separation mode: only template declaration template <typename type> type min (Type T1, Type T2) is provided ); // model2.c // The template definitionexport template <typename type> type min (Type T1, Type T2 ){/*... * //} // user. C # include "model2.h" int I, j; double D = min (I, j); // usage, an instance is required

> The keyword export indicates that the compiler needs to define this template when generating a function template instance used by other files (an exported function template). The compiler must ensure that the template definition is visible;
(Some compilers may not require export; Standard C ++ requires that export be marked before template)

The keyword export is not required in the header file template declaration; (required in CPP implementation)

A template function can only be defined as export once. The Compiler processes only one file at a time and cannot detect the situation where the template function is defined as export in multiple text files. Possible situations:
1) the link is incorrect. The function template is defined in multiple files;
2) the compiler instantiates a function template for the real parameter set of the same template multiple times. The function template instance is repeatedly defined and the link is incorrect;
3) the compiler may only use one of the export function templates to define the instantiated function templates and ignore other definitions;

NoteNot all compilers support the separation mode. (vc2010 and G ++ do not)

10.5.3 explicit instantiation Declaration

Explicit instantiation declaration helps control and reduce the time when the compiler instantiates the template multiple times and reduces the compilation time;

template <typename Type>Type sum( Type op1, int op2 ) { /* ... */ }template int* sum<int*>(int*, int);

The explicit instantiation Declaration can only appear once in the program, and the definition of the function template must be visible;

Explicit instantiation declaration is used together with a compilation option, which suppresses the implicit instantiation of templates in the program; e.g. /FT-; (explicit instantiation declaration is required in this mode)


10.6 explicit template features

Explicit and special template definition: explicit specialization definition;

Template <class T> T max (T T1, t T2) {return (T1> T2? T1: t2);} // specializetypedef const char * PCC; Template <> PCC max <PCC> (PCC S1, PCC S2) {return (strcmp (S1, S2)> 0? S1: S2 );}

> With explicit features, the template does not instantiate the const char * type when the program calls Max (), but directly calls the special definition;

If the real parameters of the template can be deduced from the function parameters, the explicit and special parameters of the template can be omitted.

template<> PCC max( PCC s1, PCC s2 )

> Omit the angle brackets "<>" section;

When you use the function template for specialization, you must make all the files that use the specialization see its declaration. Otherwise, the compiler will instantiate the base template if it cannot find the specialization;
If the same program instantiates a function template instance in one file (the declaration is not visible), it calls the explicit feature in another file, and the program is invalid;

Note:Explicit and special declarations should be placed in header files and include this header file in all programs using function templates;


10.7 overload function Template

The overloaded function template may cause ambiguity;

template <typename T>int min5( T, T ) { /* ... */ }template <typename T, typename U>int min5( T, U );

> For calls like Min (1024, 1), T and U can be of the same int type, so that both templates can be instantiated; you must explicitly specify template parameters to prevent ambiguity errors;

> Min5 (t, u); the call set processed is a superset processed by min5 (t, t). Therefore, only the min5 (t, u) Statement is provided, min5 (t, t) should be deleted;

Most specific most specializedThe same Template Name and number of parameters; for different types of corresponding function parameters, one template is another superset;

template <typename Type> Type sum( Type*, int );//1)template <typename Type> Type sum( Type, int );//2)int ia[1024];// Type == int ; sum<int>( int*, int ); or// Type == int*; sum<int*>( int*, int ); ??int ival1 = sum<int>( ia, 1024 );

> 1) more special; 2) 1) superset;


10.8 reload parsing of template function instances

Function templates can be overloaded. function templates can have the same name as common functions;

// Normal function int min (INT A1, int A2) {min <int> (a1, a2 );}

> Using common functions, the program calls the special version of min (INT, INT) Whenever an integer real parameter is used;

To parse functions of common functions and function templates with heavy load:

1) generate a candidate function set;
Consider a function template with the same name as a function call. If the real parameter deduction of the template is successful, a function template is instantiated, And the template serves as a candidate function;

2) generate a feasible function set;
Reserve functions that can be called in the Candidate function set;

3) classification of type conversion;
A) if only one function is selected, call the function. B) if the call is ambiguous, remove the function template instance from the feasible function set;

4) Only common functions in a feasible function set are considered to complete the reload parsing process;
A) if only one function is selected, the function is called. B) Otherwise, the function is ambiguous;


10.9 name resolution in template Definition

The type depends on the template parameter depend on a template parameter;

In the template definition, name resolution is performed in two steps:
First, it does not depend on the template parameter name and is parsed when the template is defined; (General function e.g. Print ("string ");)
Second, it depends on the template parameter name and is parsed when the template is instantiated; (dependent on the template function; e.g. Print (type T );)

NoteThe function template designer must ensure that all templates used in the template definition provide declarations without relying on the template parameter name; otherwise, the compilation is incorrect;

In the source code, the template is instantiated at a location called the template'sInstantiation point of Instantiation;
If the template instance needs to be used multiple times, the compiler is free to select one of these instantiation points to actually instantiate the function template. Therefore, before any instance of the template is used, all necessary declarations should be given in the header file;


10.10 namespace and function Template

The function template definition can be placed in the namespace;

Namespace cplusplus_primer {// template definition is hidden in namespace template <class type> type min (type * array, int size ){/*... */} int Ai [4] = {12, 8, 73, 45}; int size = sizeof (AI)/sizeof (Ai [0]); Using cplusplus_primer :: min; // using statement min (& Ai [0], size );

If you want to provide special features for the template in the library, you must ensure that their definitions are properly placed in the namespace containing the original template definition;
1) Describe the template in the namespace of the base template;
2) modify the namespace member name with the name of the peripheral namespace;

template<> SmallInt cplusplus_primer::min<SmallInt>( SmallInt* array, int size ){ /* ... */ }


10.11 function template example

Fast sorting sort ();

# Include "array. H "template <class elemtype> void sort (array <elemtype> & array, int low, int high) {If (low 

--- End ---

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.