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

Source: Internet
Author: User

Template and generic programming-template Definition [continued]

Iv. template type parameters

Type parameters are composed of class or typename followed by specifiers. In the template parameter table,The two keywords have the same meaning., All indicate the names followed by a type.

Template type parameters can be used as type specifiers anywhere in the template,It is used in the same way as the built-in type specifiers or class type specifiers.. Specifically, it can be used to specify the return type or function parameter type, and in the function body for variable declaration or forced type conversion.

template <class T>T calc(const T &a,const T &b){    T tmp = a;    //...    return tmp;}

1. Differences between typename and class

In the function template parameter table,KeywordsTypenameAndClassSame meaning, Which can be used interchangeably. Both keywords can be used in the same template parameter table:

template <typename T, class U> calc (const T&, const U&);

It may be more intuitive to use the keyword typename instead of the keyword class to specify the template type parameter. After all, you can use the built-in type (non-class type) as the actual type parameter, and typename is more explicit.The following name is a type name.. However, the keyword typename is added to C ++ as part of the standard C ++. ThereforeOld programs are more likely to only use keywords.Class.



2. specify the type within the template Definition

Apart from defining data members or member functions,Class can also be definedType Member. For example, the container class of the standard library defines different types, such as size_type, so that we can use containers independently of machines. To use such a type within the function template, you must tell the compiler that the name we are using refers to a type. This must be done explicitly because the compiler (and program readers) cannot check whether the name defined by the type parameter is a type or a value. For example, consider the following functions:

Template <class Parm, class U> Parm fcn (Parm * array, U value) {Parm: size_type * p; // If Parm: size_type is a type, the statement is a declaration // If Parm: size_type is an object, the statement is a multiplication operation}

By default, the compiler assumes that such a name specifies the data member rather than the type.

If you want the compiler to treat size_type as a type, you must explicitly tell the compiler to do this:

template <class Parm,class U>Parm fcn(Parm *array,U value){    typename Parm::size_type *p;   //OK}

By prefixing the member name with typename, you can tell the compiler to treat the member as a type. By writing typenameparm: size_type, it is pointed out that the size_type member bound to Parm is the type name. Of course, this declaration is used to instantiate the fcn type.Added a role:Those types must have namesSize_typeMember,The Member is of the same type..

[Best practices]

It is a good idea to specify whether typename is a type. InTypePreviously specified typenameNo harmTherefore, even if typename is unnecessary, it does not matter.

// P533 exercise 16.12 template <typename IterType> typename IterType: value_typemostApr (IterType first, IterType last) {map <typename IterType: value_type, size_t> count; while (first! = Last) {++ count [* first]; ++ first;} int apper = 0; typename IterType: value_type maxAprItem; for (typename map <typename IterType: value_type, size_t >:: iterator iter = count. begin (); iter! = Count. end (); ++ iter) {if (iter-> second> apper) {maxAprItem = iter-> first; apper = iter-> second ;}} return maxAprItem ;} int main () {vector <int> ivec; int val; ifstream inFile ("input"); while (inFile> val) {ivec. push_back (val);} cout <mostApr (ivec. begin (), ivec. end () <endl ;}

// Exercise 16.13 template <typename ContainerType> void printCntanr (ContainerType contnr) {typename ContainerType: size_type n = 0; while (n! = Contnr. size () {cout <contnr [n ++] <endl ;}}

// Exercise 16.14 template <typename IterType> void printCntanr (IterType first, IterType last) {while (first! = Last) {cout <* first <endl; ++ first ;}}


V. Non-type template parameters

The template parameters do not need to be of the type.

When a function is called, non-type parameters are replaced by values. The value type isTemplate parameters.

template <class T,size_t N>void array_init(T (&parm)[N]){    for (size_t i = 0; i != N; ++i)    {        parm[i] = 0;    }}

The non-type parameter of the template isTemplate DefinitionOfConstant ValueWhen a constant expression is required, you can use a non-type parameter to specify the length of the array.

When array_init is called, the compiler takes arguments from the array.Calculate the value of a non-type parameter:

Int x [42]; double y [10]; array_init (x); // T is replaced by int; N is replaced by 42 by array_init (y); // T is replaced by double, N is replaced by 10

The compiler instantiates an array_init version for each array used in the array_init call.



Type equivalence and non-type parameters

For non-type parameters in a template, expressions with the same result are considered to be equivalent. For example, the following two array_init calls reference the same instance-array_init <int, 42>:

Int x [42]; const int sz = 40; int y [sz + 2]; // The two function instances are the same as array_init (x); array_init (y );


// P534 exercise 16.15/16 template <typename Type, std: size_t N> std: size_t getArrSize (Type (& arr) [N]) {return N ;} template <typename ArrType, std: size_t N> void printArr (ArrType (& arr) [N]) {for (std: size_t I = 0; I! = N; ++ I) {cout <arr [I] <endl ;}} int main () {int X [] = {3, 34, 5, 65, 67,7, 7}; cout <"array size is:" <getArrSize (X) <endl; cout <"array items:" <endl; printArr (X );}

6. Compile generic programs

Code when writing a templateIt is not possible to target a specific typeBut the template code always needsMake assumptions. For example, although the compare function is technically valid for any type,The instantiated version may be invalid..

Whether the generated program is legal depends on the Operations used in the function and the operations supported by the types used:

If (v1 <v2) return-1; // T type objects must support <if (v1> v2) return 1; // T type objects must support>

If compare is called with an object that does not support the <operator, the call is invalid:

Sales_item item1, item2; cout <compare (item1, item2) <endl; // Error: the program cannot be compiled.

[Careful mine]

Restrictions on Operations completed within the function TemplateThe type that can be used to instantiate the function.. The programmer's responsibility is to ensure that the type used as the real parameter of the function actually supports any operation used, and to ensure that those operations run normally in the environment where the template uses those operations!



Write type-independent code

[Best practices]

When writing template codeThe real parameter type must have as few requirements as possibleIs very beneficial.

Although simple, it illustrates two important principles for writing generic code:

1) The template parameter is referenced by const.

2) test in the function body only uses <comparison

By setting the parameter as a const reference, you can use a type that is not allowed to be copied. In addition, if a large object calls compare, this design can also make the function run faster.

Compare the following two procedures:

template <typename Type>int compare(const Type &val1,const Type &val2){    if (val1 < val2)        return -1;    else if (val1 > val2)        return 1;    return 0;}

And:

template <typename Type>int compare(const Type &val1,const Type &val2){    if (val1 < val2)        return -1;    else if (val2 < val1)        return 1;    return 0;}

The following program reduces the requirements on the types that can be used for compare functions. These types must be supported <, but do not need to be supported>



[Warning: link compilation Error]

Generally,Compile TemplateThe compiler mayError identification in three phases:

The first stage isCompile the template definition itself. In this phase, the compiler generally does not find many errors. It can detect syntactic errors such as missed semicolons or misspelling of variable names.

The second error detection time is in the CompilerSee the TemplateUseHour. At this stage, the compiler still does not have many checks. For function template calls, many compilers only check the number and type of real parameters. The compiler can detect too many or too few real parameters, you can also check whether two real parameters of the same type are of the same true type. For a class template, the compiler can check the correct number of provided template arguments.

The third time of error generation is inInstantiationOnly at this time can we find type-related errors. Manage the instantiation Method Based on the compiler,These errors may be reported at the link..

It is important to realize thatCompile the template DefinitionDoes not know whether the program is valid. Similarly, a compilation error may even occur after each file using the template has been successfully compiled. There are very few errors detected during instantiation, and the error detection may occur at the link.

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.