C ++ Primer study note _ 77 _ templates and generic programming

Source: Internet
Author: User

Templates and generic programming -- instantiation



Introduction:

A template is a blueprint and is not a class or function. The compiler uses a template to generate a specific version of a specified class or function. The process of generating a template for a specific type of instance is called Instantiation.

The template will be instantiated during use, and the class template will be instantiated When referencing the actual template type. The function template will be instantiated when calling it or using it to initialize or assign values to the function pointer.



1Class instantiation

When the Queue <int> qi is compiled, the compiler automatically creates a class named Queue <int>. In fact, the compiler creates the Queue <int> class by re-compiling the Queue template and replacing the appearance of the template parameters with the type int. The instantiated class is like the one already written:

template <typename Type> class Queue<Type>{public:    Queue();    int &front();    const int &front() const;    void push(const int &);    void pop();    bool empty() const;private:    //...};

To create a Queue class for a string object, you can write the following code:

Queue<string> qs;

In this example, the string is used to replace the Type.

[Key understanding :]

Each instantiation of a class template generates an independent class type: the Queue instantiated for the int type has no relationship with any other Queue type, and has no special access permission for members of other Queue types!



2Class template parameters are required

To use a class template, you must explicitly specify the template parameters:

    Queue qs;//Error

Class TemplateType Not Defined,Only a specific instance defines the type.. A specific instance is defined by providing a template to participate in matching of each template parameter. The template parameters are specified in the list enclosed by Angle brackets separated by commas:

    Queue<int> qi;    Queue<string> qs;

The type defined by the template class always contains the real parameters of the template. For example, Queue is not a type, while Queue <int> and Queue <string> is a type.



3Function template instantiation

When using a function template, the compiler usually deduce the real parameters of the template for us:

Int main () {compare (1, 0); // Replace the template parameter with int compare (3.14, 2.7); // Replace the template parameter with double}

This program instantiates two versions of compare: one uses int instead of T, and the other uses double instead of T.The compiler has compiledCompareThese two instances:

int compare(const int &v1, const int &v2){    if (v1 < v2)        return -1;    if (v2 < v1)        return 1;    return 0;}int compare(const double &v1, const double &v2){    if (v1 < v2)        return -1;    if (v2 < v1)        return 1;    return 0;}

1. Real parameter inference of the template

To determine which function should be instantiated, the compiler will view each real parameter. If the corresponding parameter is declared as the type of the type parameter, the compiler deduce the type of the parameter from the type of the real parameter. Determine the real parameters of the template from the real parameters of the FunctionTypeAndValueThe process is calledTemplate real parameter Inference.



1. The real parameters of multiple types of parameters must be completely matched.

Template type parameters can be usedType of more than one function parameter. In this case, the template type inference must be for each correspondingFunction argumentsGenerateSame template real parameter type.

Template <typename T> int compare (const T & val1, const T & val2) {if (val1 <val2) return-1; else if (val2 <val2) return 1; return 0;} int main () {short si; compare (si, 1024); // Error: the actual parameter type for calling compare is different and cannot be inferred correctly}

If the compare designer wants to allow regular conversion of real parameters, the function mustTwo types of parameters are used for definition.:

template <typename T,typename U>int compare(const T &val1,const U &val2){    if (val1 < val2)        return -1;    else if (val2 < val2)        return 1;    return 0;}int main(){    short si;    compare(si,1024);   //OK}

2Limited conversion of real parameters of the type parameter

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

1) const conversion: functions that accept const references or const pointers can be called using non-const object references or pointers, without generating new instantiation. If the function acceptsNon-reference typeThe actual parameters of the form parameter type ignore the const, that is, whether the const or non-const object is passed to the function that accepts the non-reference type, the same instantiation is used.

2) array or functionTo 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.ArrayReal participants will be treated as pointingPointer of the first element,FunctionReal parameter as pointingPointer of Function Type.

Template <typename T> T fobj (T, T); template <typename T> T fref (const T &, const T &); string s1 ("a value "); const string s2 ("another value"); fobj (s1, s2); // OK: call fobj (string, string), real parameter copied fref (s1, s2 ); // OK: cal fref (const string &, const string &) int a [10], B [42]; fobj (a, B); // OK: call fobj (int *, int *) fref (a, B); // Error: the real parameter cannot be converted to pointer [pointer]

3Applies to regular conversions of non-template real parameters

Note the following procedure:

template <typename Type>Type sum(const Type &op1,int op2){    return op1 + op2;}

Because the op2 type is fixed, regular conversion can be applied to the real parameters passed to op2 when sum is called:

Double d = 3.14; string s1 ("hiya"), s2 ("world"); cout <sum (1024, d) <endl; cout <sum (1.4, d) <endl; cout <sum (s1, s2) <endl; // Error: no conversion from string to int

4Template real parameter inference and function pointer

You can use the function template to initialize or assign values to function pointers. In this case, the compiler uses the pointer type to instantiate the template version with the appropriate template parameters.

For example, assume that there is a function pointer pointing to the function that returns the int value. This function accepts two parameters, both of which are referenced by constint. You can use this pointer to point to compare instantiation:

template <typename T>int compare(const T &,const T &);int (*pf1)(const int &,const int &) = compare;

Pf1Is a pointer., Pointing to the "function that accepts two constint & type parameters and returns the int value ",Class of the ParameterType determinesTType of template parameters: The real parameters of the T template are int type. The pointer pf1 references the instantiation of binding T to the int.

ObtainAddress of function template instantiationThe context must be as follows:It allows you to determine a unique type or value for each template parameter.

If the real parameters of the template cannot be determined from the function pointer type, an error occurs:

Void func (int (*) (const string &, const string &); void func (int (*) (const int &, const int &)); func (compare); // Error: it is impossible to determine the unique type of the real parameter of the template by viewing the form parameter type of func.

The call to func can instantiate Any of the following functions:

compare(const string&, const string&) compare(const int&, const int&)

Because the unique instantiation cannot be determined for the real parameters passed to func, this call will generate a compile-time (or link-Time) error!

// P540 exercise 16.22 template <class Type> Type calc (const Type * arr, int size); template <class Type> Type fcn (Type p1, Type p2 ); int main () {double dobj; float fobj; char cobj; int ai [5] = {343,}; calc (& cobj, 'C '); calc (& dobj, fobj); fcn (ai, ai + sizeof (ai)/sizeof (* ai ));}

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.