26. c ++ primer 4th notes, templates and generic programming (1)

Source: Internet
Author: User

1Generic programming is written independently of any specific type.Code. Use genericProgram, WeYou need to provide the type or value operated by the specific program instance.

In generic programming, the classes and functions we write can be PolymorphismUsed to span unrelated types during compilation.

2Templates are the basis of generic programming.

3,The polymorphism of object-oriented programming is called "running" polymorphism, which is applied to classes with inheritance relationships.We can write such code to ignore the type difference between the base class and the derived class.

The polymorphism on which generic programming depends is known as the Polymorphism or parametric polymorphism at compilation..

4Template definition with keywordsTemplateStart, followed by the template parameter table. The template parameter table is a list of one or more template parameters enclosed by Angle brackets. The parameters are separated by commas.

The template parameter table cannot be blank..

Sample Code

 
Template <typename T> returntype functionname (parameter_list ){//..}

5Template parameters can be type parameters or non-type parameters that represent constant expressions. Non-type parameters follow the type description.

6,When using the function template, the compiler will infer that (or those) the real parameters of the template are bound to the template parameters.Once the compiler determines the actual template arguments, it is calledAn instance of the instantiated function Template.

7,InlineFunction Template

Declaration like a non-template function; note:Inline.

Example

// OK: inline specifier follows template parameter listtemplate <typename T> inline T min (const T &, const T &); // error: incorrect placement of inline specifierinline template <typename T> T min (const T &, const T &);

8, Class template

Like a function template, addTemplate <class type>.

9, Which can be assigned to the template parametersThe only difference is whether the parameter is a type parameter or a non-type parameter.. If it is a type parameter, we know that this parameter represents an unknown type. If it is a non-type parameter, we know that it is an unknown value.

10Scope: The name of a template parameter can be used after it is declared as a template parameter until the end of the template declaration or definition.The template parameters follow the regular name blocking rules.. The name used as the template parameter cannot be reused within the template, and can be reused in different templates.

11, Can be declared only, does not define the template. In the Declaration and definition of the same template, the template parameter name does not need to be the same.Each template type parameter must be preceded by a keywordTypename/class,Each non-type parameter must be preceded by a type name.

Sample Code

// All three uses of calc refer to the same function template // forward declarations of the templatetemplate <class T> T calc (const T &, const T &); template <Class U> U calc (const U &, const U &); // actual definition of the templatetemplate <class type> type calc (const type &, const type & B ){/*... */}

12Template type parameters can be used anywhere in the template as type specifiers: return type, function parameter type, variable declaration, forced type conversion.

13,TypenameAndClassSame meaning, whileTypenameMore intuitive.

14The name defined by the type parameter may be a type or a member value. To passTypenameShow notification compiler This is a type.

Example

 
Template <class parm, Class U> parm FCN (parm * array, U value) {parm: size_type * P; // If parm: size_type is a type, then a declaration // If parm: size_type is an object, then multiplication // typename parm: size_type * P // OK, declares P to be a pointer}

15, Non-type parameters: When a function is called, the non-type parameters will be replaced by values, and the value type is specified in the template parameter table.

Example

 
// Initialize elements of an array to zerotemplate <class T, size_t n> void array_init (T (& parm) [N]) {for (size_t I = 0; I! = N; ++ I) {parm [I] = 0; cout <I <Endl ;}} int main () {int X [42]; array_init <int, 42> (x); // instantiates array_init (INT (&) [42]) // array_init (x );//... return 1 ;}

For non-type parameters of the template, expressions with the same result will be considered as equivalent..

16When writing template code, it is helpful to have as few requirements on the real parameter type as possible.

17The process of generating a template for a specific type of instance is called Instantiation. The template will be instantiated during use. The class template will be instantiated When referencing the actual template class type. The function template will be instantiated when calling it or using it to initialize or assign values to the function pointer.

18, Each instantiation of the class template will produce an independent class type.The specific instantiation of a class template is defined by providing a template to participate in matching of each template's form parameter. When using a function template, the compiler usually deduce the real parameters of the template for us.

19The process of determining the type and value of template real parameters from function real parameters is called template real parameter inference. Multiple types of form parameters must be completely matched.

20In general, real parameters are not converted to match existing instantiation, and new instances are generated. In addition to new instantiation, the compiler only performs two conversions.

1)ConstConversion: acceptConstReference orConstPointer functions can use non-ConstYou do not need to create a new instance. If the function accepts a non-reference type, the form parameter type and the real parameter are ignoredConst, That isConstOr notConstThe same instantiation is used for all functions that receive non-reference types.

2) Array or function to pointer conversion:If the template parameter is not of the reference type, the regular pointer conversion is applied to the real parameters of the array or function type. Array arguments are treated as pointers to their first element, and function arguments are treated as pointers to function types.

Example

 
Template <typename T> T fobj (t, t); // arguments are copiedtemplate <typename T> T fref (const T &, const T &); // reference argumentsint main () {string S1 ("A value"); const string S2 ("another value"); fobj (S1, S2); // OK: cils f (string, string), const is ignoredfref (S1, S2); // OK: non const object S1 converted to const referenceint A [10], B [42]; fobj (a, B); // OK: callf (int *, int *) fref (a, B); // error: array types don't match; arguments aren't converted to pointersreturn 1 ;}

When the parameter is a reference, the array cannot be converted to a pointer.

21, The type conversion restrictions only apply to those real parameters whose types are template parameters. Common conversions can be used for common type-defined parameters.

Example

Template <class type> type sum (const type & OP1, int OP2) {return OP1 + OP2;} int main () {double D = 3.14; string S1 ("hiya"), S2 ("world"); sum (1024, d); // OK: instantiates sum (INT, INT ), converts d to INTSUM (1.4, d); // OK: instantiates sum (double, INT), converts d to INTSUM (S1, S2); // error: s2 cannot be converted to intreturn 1 ;}

22You can use the function template to initialize or assign values to function pointers.

Example

 
Template <typename T> int compare (const T &, const T &); // pf1 points to the instantiation int compare (const Int &, const Int &) int main () {int (* pf1) (const Int &, const Int &) = compare; return 1 ;}

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.