C + + Template learning

Source: Internet
Author: User
Tags function definition

1. What is 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.

//函数1.intmax(int x,int y);{return(x>y)?x:y ;}//函数2.floatmaxfloat x,float y){return (x>y)? x:y ;}//函数3.doublemax(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, the function template writing

The general form of a function template is as follows:

Template <class或者也可以用typename T>返回类型 函数名(形参表){//函数定义体 }

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.
As an example:

//test.cpp#include <iostream>using STD::cout;using STD:: Endl;//Declare a function template to compare the size of the parameters of the input two of the same data type, class can also 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 integer:"<<min (N1,N2) <<endl;cout<<"Smaller real numbers:"<<min (D1,D2) <<endl; System"PAUSE");}

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 to type templates

Define a class Template:

class或者也可以用typename T >class类名{//类定义......};

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.
As an example,

//ClassTemplate.h#ifndef classtemplate_hh#define CLASSTEMPLATE_HHTemplate<TypeNameT1,TypeNameT2>classmyclass{Private: T1 I; T2 J; Public: MyClass (T1 A, T2 b);//constructor     voidShow ();};//This is a constructor//Note these formatsTemplate<TypeNameT1,TypeNameT2>myclass<t1,t2>::myclass (T1 a,t2 B): I (a), J (b) {}//This is void Show ();Template<TypeNameT1,TypeNameT2>voidMyclass<t1,t2>::show () {cout<<"i="<<I<<", j="<<j<<endl;}#endif//Test.cpp#include <iostream>#include "ClassTemplate.h"using STD::cout;using STD:: 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.

template<typenameint MAXSIZE>class Stack{Private:       T elems[MAXSIZE];…};Int main(){       Stack<int20> int20Stack;       Stack<int40> int40Stack;…};
5. Use 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<TypeNameT>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);}

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.

6, template of the special

If we are going to write a function for a particular type of template function (class), we need to use the template's specificity, such as when we are going to call Max with a long type, and return a small value (forgive me for the inappropriate example):
Template<>//This represents the following is a template function
Long Max (long A, long B)//For VC, here is can be omitted
{
Return a > B? b:a;
}
In fact, the so-called special, is to replace the compiler to complete the specific type of work, the modern template Library, a large number of use of this technique.
For partial specificity, only some of the types in the template type are specific, such as

Template

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

C + + Template learning

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.