C + + study notes (14): Templates

Source: Internet
Author: User

A template is a tool for implementing a code reuse mechanism that implements type parameterization, which defines a type as a parameter, enabling true code reusability.
Template can be divided into two categories, one is a function template, the other is a class template.
The corresponding technology in Java is called generics.

Function templates:

Format:

1 template <class parameter name,class parameter name,......>2 return type function name (parameter list)3 {4     function Body 5 }

Where template and class are related to the word,class can be used typename to see the word instead , here TypeName and class no difference,<> the parameters in parentheses are called template parameter, template parameter and function parameter is very similar, The template parameter cannot be empty.
Once you declare a template function, you can use the formal parameters of the template function to name the member variables and member functions in the class, that is, the template parameter names can be used wherever the built-in type is used in the function.

For example:

1#include <iostream>2 3 usingstd::cout;4 usingStd::endl;5 6 //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,7 //T can be replaced by any letter or number. 8Template <classT>9 t min (t x,t y)Ten { One      return(x<y)?x:y; A } -  - voidMain () the { -      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"); +}

Class Template:

Format:

1 template<class parameter name, class parameter name,...>2 class name 3 {4    ... 5 };

Both the class template and the function template are made up of template parameter lists starting with the template, which cannot be empty, but declaring a class template can be used to name the member variables and member functions in a class template, that is, a template parameter name can be used where a built-in type can be used in a class.

The methods for defining member functions outside the class template are:

1 template< template parameter list > function return type class name < template parameter name;:: function name (argument list) {function Body}

For example, if a class A with two template parameter t1,t2 contains a void h () function, the syntax for defining the function is:

1 template<class T1,classvoid a<t1,t2>::h () {}

Example:

1 //ClassTemplate.h2 #ifndef classtemplate_hh3 4 #defineClasstemplate_hh5 6Template<typename T1,typename t2>7 8 classmyclass{9 Ten Private: One  A T1 I; -  - T2 J; the  -  Public: -  -MyClass (T1 A, T2 b);//Constructor +  -      voidShow (); +  A }; at  - //This is a constructor - //Note these formats -Template <typename T1,typename t2> -Myclass<t1,t2>:: MyClass (T1 a,t2 B): I (a), J (b) {} -  in //This is void Show (); -Template <typename T1,typename t2> to voidMyclass<t1,t2>:: Show () + { -  thecout<<"i="<<I<<", j="<<J<<Endl; *  $ }Panax Notoginseng  - #endif the  + //Test.cpp A  the#include <iostream> +  -#include"ClassTemplate.h" $  $ usingstd::cout; -  - usingStd::endl; the  - voidMain ()Wuyi  the { -  Wumyclass<int,int> Class1 (3,5); -  About class1.show (); $  -myclass<int,Char> Class2 (3,'a'); -  - class2.show (); A  +myclass<Double,int> Class3 (2.9,Ten); the  - class3.show (); $  theSystem"PAUSE"); the  the}

Formal parameters of a template

(1) type parameter

Type parameters are made up of the closing word class or typename followed by specifiers.
The template parameter represents an unknown type.
A template type parameter can be used as a type description trailing characters anywhere in the template, in exactly the same way as a built-in type specifier or class type specifier, that is, you can use to specify return types, variable declarations, and so on.

Such as:

1 template<classvoid H (T a) {}; // where T is a type parameter, and the name of the type parameter is self-determined by the user

(2) Non-type parameters

    1. The template's non-type parameter is the built-in type parameter, such as Template<class T, int a> class b{}, where int A is a non-type template parameter.
    2. A non-type parameter is a constant value inside the template definition, meaning that the non-type parameter is constant inside the template.
    3. The formal parameters of non-type templates can only be integers, pointers and references, such as double,string, String * * Such types are not allowed. But Double &,double *, the object's reference or pointer is correct.
    4. An argument that calls a non-type template parameter must be a constant expression, that is, he must be able to calculate the result at compile time.
    5. Any local object, local variable, the address of a local object, or the address of a local variable is not a constant expression and cannot be used as an argument for a non-type template parameter. Global pointer type, global variable, global object is not a constant expression, and cannot be used as an argument for a non-type template parameter.
    6. The address or reference of a global variable, the address of a global object, or a reference to a const type variable is a constant expression that can be used as an argument for a non-type template parameter.
    7. The result of a sizeof expression is a constant expression that can also be used as an argument to a non-type template parameter.
    8. When the template's formal parameter is an integer, the argument that is called when the template must be integral, and constant during compilation, such as template <class T, int a> class a{}, and if there is an int B, then a<int, b> m; Because B is not a constant, if const int B, then a<int, b> m, is correct, because then B is a constant.
    9. Non-type parameters generally do not apply to function templates, such as a function template template<class T, int a> void H (t b) {}, if the use of H (2) call will be unable to the non-type parameter a parameter error, For this template function can be resolved with the display template arguments, such as with H<int, 3> (2) so that the non-type parameter A is set to an integer 3. The display template arguments are described later.

Conversions allowed between formal parameters and arguments for non-type template parameters:

    • Allows conversion from an array to a pointer, from a function to a pointer. such as: Template <int *a> class a{}; int b[1]; A<b> m; that is, array-to-pointer conversion
    • The conversion of the Const modifier. such as: Template<const int *a> class a{}; int b; A<&b> m; That is, the conversion from int * to const int *.
    • Promote conversions. such as: Template<int a> class a{}; const short b=2; A<b> m; That is, the ascending conversion from short to int
    • Integer value conversion. such as: template<unsigned int a> class a{}; A<3> m; That is, the conversion from int to unsigned int.
    • General conversions.

(3) Template parameters (template as a template parameter)

is to use a template as a parameter to another template.
Example:

1 grid<int,vector<int> > myintgrid;  

Note that int appears two times, and you must specify that the grid and vector element types are int.
If written as:

1 grid<int,vector> Myintgrid;  

Because the vector itself is a template, not a type, so this is a template template parameter. Specifying a template template parameter is a bit like specifying a function pointer parameter in a regular function.
function pointer types include the return type and the parameter type of the function. Also include the full template declaration when declaring template template parameters:
The first thing to know is the prototype of the template as a parameter, such as vector

1 template<typename e,typename allocator=allocator<e> >  2class  Vector  3 {...};  

You can then define:

1 template<typename t,template<typename e,typename allocator=allocator<e> >class Container=vector>  2class  Grid  3{   4  Public:  5  //omitted for brevity  6  container<t>* mcells;   7 };  

C + + study notes (14): Templates

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.