Templates for C + +

Source: Internet
Author: User

C + + templates are divided into functional templates and class templates. In fact, the template is a type of parameterized tools.
First, function template1. Declaration Definitions for Function Templates

Template<typename/class T1,typename/class T2,.... >

return type function name (function parameter) {

function body

}

For example:

Template<typename t>t Add (T t,t t1) {       return t+t1;}

2. Two ways to call template functions(1) Implicit invocation

       int i=1,j=2;       int K=add (I,J);

The default is that the two parameters of the Add function are the same type, and the system determines the specific type of the formal parameter based on the type of the actual argument at the time of the call. Note that the two parameter types must be the same here.

No:

       int i=1,j=2;       int K=add (1,2.2);//error

(2) Show call

       int i=1,j=2;       int k=add<int> (I,J);

The specific type of the function template is specified first, and then called. This will allow you to:

       int k=add<int> (1,2.3);//ok
the difference between this and the implicit invocation is that the call is to specify the specific type of the function template, then the function becomes a function of the specific type, and intadd (int t,int t1) then calls Add<int> (1,2.3); Obviously there is no problem. It's just a bit of a system-type conversion.

Second, class template

1. Declaration definitions for Class templates

Template<typename/class T1, Typename/class T2,.... >

Class Name {

Members of the class

}

For example:

Template<typename T>class a{public:a (t B): A (b) {}          T swap (t& i,t& j) {                 T temp;                 temp=i;                 I=j;                 j=temp;          }          void foo (Tt);p rivate:t A;}; Template<typename t>void A<t>::foo (T t) {Cout<<t<<endl;}

(1) Note the member functions of the class template, if implemented outside of the class, must precede the implementation with template<...>. and the name of the letter "class name <t1[,t2,...] > ".

(2) When in a class, when you want to use an object of its own class (for example: Copy construct, operator=), use the class name directly. For example:

Class A{public:a (T B): A (b) {}          A (const a&c) {                 a=c.a;          } Private:t A;};

(3) When you want to use this class name outside of the class, you must "class name +<t,.... >". For example, when a member function is implemented outside of the class, the function name is added in front of the object.

Class A{public:a (T B): A (b) {}          void foo (Ac);p rivate:t A;}; Template<typename t>void A<t>::foo (a<t>t) {Cout<<t<<endl;}

(4) Sometimes objects in a class that want to use the same template for other types of classes. For example:

Class A{public:a (T B): A (b) {}          T Getm () {Returna;}          Template<typename y>          Voidfoo (a<y>& c) {                 Cout<<c.getm () <<endl;          } Private:t A;}; int _tmain (int argc, _tchar* argv[]) {       a<int> A (2);       A<double> B (3);       A.foo (b);       System ("pause");       return 0;}


Add Template<typenamey> to the front of the function, and note that Y cannot be the same as the T in the class template.

This is often the case when rewriting copy and operator=, which is often used when objects of the subclass are constructed and assigned to the parent class's object copy. Concrete visible auto_ptr source code.

2. Invocation of class templates

         A<int>a (2);

When defining a Class object, first declare the concrete type of the class.

(1) The implicit invocation of the function template is not the same, you can:

Template<typename T>class a{public:a (t B): A (b) {}          t Add (t T1, T T2)          {returnt1+t2;} Private:t A;}; int _tmain (int argc, _tchar* argv[]) {       a<int> A (2);       A.add (2,3.4);//ok       System ("pause");       return 0;}

Notice the principle of the class template here: Since the class template has defined the type of T at the time of definition, so after defining a<int> a (2), the T in a becomes int, so the Add function becomes int add (int t1,int t2). This obviously can be called by Add (2,3.4), conforming to the system's default type conversions.

Third, non-type parameters

When Template<typenamet,int in>. When a specific type such as int occurs, in is the non-type parameter. For example:

Template<typename t,int in>class a{public:a () {a=new t[in];a[0]=3;}          void foo ()          {Cout<<a[0]<<endl;}          ~a () {delete[]a;} Private:t* A;}; int _tmain (int argc, _tchar* argv[]) {       a<int,4> A;       A.foo ();       System ("pause");       return 0;}

1. Note that the non-type parameter in is internally a constant value, as can be seen in the code above.

2. A non-type parameter can only be an integral type (including int,short,unsigned int), a pointer, and a reference . This means that it cannot be float/double/string, but it can be a pointer to a double*/double&/object, and a reference is also possible.

Class B{};template<typename T,doublein>class a{};//errortemplate<typename t,floatin>class A{};// Errortemplate<typename t,b in>classa{};//errortemplate<typename T,double&in>class A{};//OKtemplate <typename t,double*in>class a{};//oktemplate<typename t,b* In>classa{};//ok

3. An argument that calls a non-type parameter must be a constant expression . The results can be computed at compile time. (Note that sizeof's return value is also constant and can be used)

Note : What is a constant expression? (The value will not change and the exact value will be known at compile time)

const int, constant, enumeration. The reference/address of the global variable, the reference/address of the global object.

is not a constant expression:

Local variables, local objects, address/references of local objects, global variables, global objects are not constant expressions.

Summary: first a non-type parameter can only be an integer, a pointer, a reference. This also determines that the argument must be the only one, except that the argument must also be a constant expression. So a rollup: an argument can only be a const int, a constant, an enumeration, a reference/address to a global variable, a reference/address to a global object.

You can also:

template<int* t>class a{};int d[]={2};int _tmain (int argc, _tchar* argv[]) {       a<d>a;//----------OK       System ("pause");       return 0;}

4. Templates with non-type parameters when implementing member functions outside the class:

In fact, for all types of class templates, when you define a member of a class outside of the class, the template parameters after the templates should match the template parameters of the class you are defining .

template<int* a>class a{public:void foo ();}; template<int* a>  -----Don't casually modify the name of a outside of the class. Maintain and define consistent void A<a>::foo () {}

Iv. you can provide a default value of type for a class template

Template<typename t=int>class a{};int _tmain (int argc, _tchar* argv[]) {       A<>a;//ok       a<double > B;//ok       System ("pause");       return 0;}

1. Note You can provide a type default value for a class template, and you cannot provide a type default value for a function template.

Template<typename t=int>//errorvoid foo () {}

2. Note that when there are more than one type parameter, the default value is provided from the parameter after the first parameter that provides the default value.

Template<typename t=int,typename T1>//errorclass a{};

V. the specificity of the template

1. The specificity of the template is to perform special operations when a special type is given to an existing template.

Template<typename t>class a{public:void foo () {cout<< "T" <<endl;}}; template<>//of the template, when T is int, this is performed when other types are executed with the above class a<int>{public:void foo () {cout<< "int" < <endl;}}; int _tmain (int argc, _tchar* argv[]) {       a<int> a;//executes the following special template       A.foo ();       A<double> b;//executes the above common template       b.foo ();       System ("pause");       return 0;}

2. The partial specificity of the template is also called partial specificity. When a template has more than one formal parameter, a portion of it is customized. I want to correspond with all the above special.

1. Standard template class. Template<typename T1, Typenamet2>class MyClass {...};//2. Two template parameters have partial special classes of the same type. Template<typename t>class myclass<t,t> {...};//3. The second type parameter is Inttemplate<typename T>class MyClas s<t,int> {...};//4. Two template parameters are pointers. Template<typename t1,typenamet2>classmyclass<t1*,t2*> {...};//5. Two template parameters are pointers of the same type. Template<typename t>class myclass<t*,t*>{...};//6. All the specificity of the template, the above 2~5 as part of the special Template<>class MyClass& Lt;int,double>{...};         int _tmain (int argc, _tchar* argv[]) {myclass<int,float>c1;    Call myclass<t1,t2> myclass<float,float> C2;      Call Myclass<t,t> myclass<float,int> C3;    Call Myclass<t,int> myclass<int*,float*>c4;      Call Myclass<t1*,t2*> myclass<int*,int*>c5;      Call Myclass<t*,t*> myclass<int,double>c6;       Call myclass<int,double> System ("pause"); return 0;}


All of the special is generally template<>. There is nothing in the brackets, all the formal parameters are special.

Part of the special is generally template<t,... >. There's something in the brackets that doesn't make all the formal parameters special.

Function templates can also be customized in the same vein.

Vi. Overloading of function templates

Class templates are not overloaded, and function templates can be overloaded.

Example:

Template<typename t>void foo (T) {cout<< "template" <<endl;} void foo (int) {cout<< "foo" <<ENDL;} int _tmain (int argc, _tchar* argv[]) {       int i=2;       Double j=2.0;       Foo (i);//The Call is foo (int)------(1)       foo (j);//Call is Template<>foo (T)----------(2)       system ("pause")       ; return 0;}


Similar to the specificity, except that class templates cannot be overloaded. (Nonsense, can the class overload?)

Overload selection Order: "More special, higher priority"

Obviously if (1) says so: "foo<int> (i);" is to explicitly invoke the function template so that it calls the Tempalte<>foo (T);

Templates for C + +

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.