C + + templates (i)

Source: Internet
Author: User

1. the concept of a template.

We have learned overload (overloading), for overloaded functions, the check mechanism of C + + can be different from the function parameter and the owning class. Call the overloaded function correctly. For example, to find the maximum value of two numbers, we define the max () function to define different overloaded (overload) versions of different data types separately.

 //  function 1.  int  Max (int  x, int  y); {return  (x>y)? x:y;}  //  function 2.  float  Max (float  x,float  y) {return  (x>y)?  x:y;}  //  function 3.  double  Max (double  x,double  y) {return  (C>y) x:y;} 

But if in the main function, we define a char, a, a, respectively; Then, when you execute Max (A, b), the program will go wrong because we do not have an overloaded version of the char type defined.

Now, we re-examine the max () function above, they all have the same function, that is, to find the maximum value of two, can write a set of code to solve the problem? This avoids the invocation error caused by the overloaded function definition. In order to solve the above problems, C + + introduces template mechanism, template definition: template is a tool to implement code reuse mechanism, it can implement type parameterization, that is, the type is defined as a parameter, thus realizing the real code reusability. Template can be divided into two categories, one is a function template, the other is a class template.

2. How function templates are spelled

The general form of a function template is as follows:

Template <class or you can use typename t>

return type function name (formal parameter list)
{//function definition Body}

Description: Template is a keyword that declares templates, which declares that a template keyword class cannot be omitted, and if the type parameter is extra, the class < type parameter list > can contain the base data type can contain the class type, before each parameter.

Please see the following procedure:

//Test.cpp#include<iostream>usingstd::cout;usingStd::endl;//declare a function template to compare the size of the parameters of the input two of the same data type, class can be replaced by TypeName,//T can be replaced by any letter or number. Template<classT>t min (t x,t y) {return(x<y)?x:y;}voidMain () {intn1=2, n2=Ten; Doubled1=1.5, d2=5.6; cout<<"smaller integers:"<<min (N1,N2) <<Endl; cout<<"minor real numbers:"<<min (D1,D2) <<Endl; System ("PAUSE");}

Program Run Result:

 

Program Analysis: the main () function defines two integer variable n1, n2 two double type variable d1, d2 then calls Min (N1, N2); That is, the instantiation function template T min (t x, t y) where T is of type int, the minimum value in the N1,N2 is calculated. When you call min (d1,d2), the minimum value in the D1,D2 is calculated.

3. How the class template is spelled

Define a class Template:

Template < class or you can also use typename T >
Class Name {
Class definition ...
};

Description: where the template is a keyword that declares templates, it declares a template, the template parameter can be one, or it can be multiple.

For example, define a class template:

//ClassTemplate.h#ifndef classtemplate_hh#defineClasstemplate_hhTemplate<typename T1,typename t2>classmyclass{Private: T1 I; T2 J; Public: MyClass (T1 A, T2 b);//Constructor     voidshow ();};//This is a constructor//Note these formatsTemplate<typename T1,typename t2>MyClass<T1,T2>:: MyClass (T1 a,t2 B): I (a), J (b) {}//This is void Show ();Template<typename T1,typename t2>voidMyclass<t1,t2>:: Show () {cout<<"i="<<I<<", j="<<J<<Endl;}#endif//Test.cpp#include<iostream>#include"ClassTemplate.h"usingstd::cout;usingStd::endl;voidMain () {MyClass<int,int> Class1 (3,5);     Class1.show (); MyClass<int,Char> Class2 (3,'a');     Class2.show (); MyClass<Double,int> Class3 (2.9,Ten);     Class3.show (); System ("PAUSE");}

4. Non-type template parameters

In general, a non-type template parameter can be a constant integer (including an enumeration) or a pointer to an externally linked object.

That is, floating-point numbers do not work, and pointers to internal linked objects are not possible.


int Maxsize>class  stack{private:       int  main () {       Stack<int > int20stack;       Stack<intint40stack > ...};

5. Using the template type

Sometimes the template type is a container or a class, to use the type under that type can be called directly, the following is a printable STL in the order and chain of the container template function

Template <typename t>voidprint (T v) {t::iterator itor; for(Itor = V.begin (); Itor! = V.end (); + +itor) {cout<< *itor <<" "; } cout<<Endl;}voidMainintargcChar**argv) {List<int>l; L.push_back (1); L.push_front (2); if(!l.empty ()) print (L); Vector<int>Vec; Vec.push_back (1); Vec.push_back (6); if(!vec.empty ()) print (VEC);}

Print results

Implicit type conversions for type deduction
Before deciding on the template parameter type, the compiler performs the following implicit type conversions:

Left-value transformation
Modifier Word Conversion
Conversions from a derived class to a base class

See "C + + Primer" ([note 2],p500) for a complete discussion of this topic.

In short, the compiler weakens certain types of properties, such as the Lvalue property of the reference type in our example. For example, a compiler uses a value type to instantiate a function template instead of using the appropriate reference type.

Similarly, it instantiates a function template with a pointer type, rather than the corresponding array type.

it removes the const modifier, never instantiates a function template with a const type , always uses the corresponding non-const type, but for pointers, pointers and const pointers are different types.

The bottom line is that automatic template argument deduction contains type conversions, and some type properties are lost when the compiler automatically determines template parameters. These type properties can be persisted when using explicit function template parameter declarations.

Original link: http://www.cnblogs.com/gaojun/archive/2010/09/10/1823354.html

C + + template (i)

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.