C + + template (ii) "Go"

Source: Internet
Author: User

This article transferred from: http://www.cnblogs.com/gw811/archive/2012/10/25/2738929.html

C + + templates

Templates are tools that support parameterized polymorphism in C + +, using templates that enable users to declare a generic pattern for a class or function so that some data members or member functions in a class get arbitrary types of parameters and return values.

A template is a tool for parameterization of types ;

There are usually two kinds of forms: function Templates and class templates ;

function templates for functions with different parameter types only;

Class templates are for classes that differ only in data members and member function types .

  The purpose of using templates is to allow programmers to write type-independent code. For example, to write a swap function that swaps two int types, this function can only implement the int type, the type of double, the characters cannot be implemented, and to implement these types of exchanges, we need to rewrite another swap. function. The purpose of using a template is to make the implementation of the program independent of the type, such as a swap template function, that can achieve the int type, but also can achieve a double type of exchange. Templates can be applied to functions and classes. The following are described separately.

  Note: The declaration or definition of a template can only be done within a global, namespace, or class scope. That is, it cannot be done within a local scope, such as a template cannot be declared or defined in the main function.

I. General formula of function template

1. Format of function Template:

    Template <class parameter name, class parameter name,......> return type function name (argument list)

{

function body

}

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 arguments in the <> brackets are called template parameters, the template parameters and function parameters are very similar, and 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. The template parameter requires the template arguments provided when the template function is called to initialize the template parameter, and once the compiler determines the actual template argument type, it is called an instance of the function template. For example, the form of swap template function is

      Template <class t> void Swap (t& A, t& b) {},

When such a template function is called, the type T is replaced by the type of the call, such as swap ( A, a , b ) where A is the type int , and the formal parameter in the swap of the template function T is replaced by int , and the template function becomes swap (int &a, int &b). When swap (c,d) where C and D are double types, the template function is replaced with a swap (double &a, double &B), which enables the implementation of the function with type-independent code.

2, note: For the function template does not have a call of H (int,int) , cannot specify the type of template parameter in the parameters of the function call, the call to the function template should be done using argument deduction , that is, only h (2,3) Such a call, or an int a, B, H (A, A, a).

  A sample demonstration of the function template will be covered in the following article!

Ii. class template General formula

1. The format of the class template is:

Template<class parameter name, class parameter name,...> class name

{ ... };

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 member variables and member functions in a class with the formal parameters of the class template. That is, where you can use built-in types in your class, you can declare them using template parameter names. like

    Template<class t> class A{public:t A; T b; t hy (t C, t &d);};

In class a , two member variables a and bare declared with a type T , and a return type of T with two parameter type T is declared. The function of hy.

2, the creation of class template objects: For example, a template class a, the use of class template to create an object is a<int> m; Follow the <> angle bracket followed by class a and fill in the appropriate type, so that all the template parameters in class a are replaced by int . When the class template has two template parameters, the method for creating the object is A<int, double> m; Types are separated by commas.

3. For a class template, the type of the template parameter must be explicitly specified in the angle brackets after the class name. such as a<2> m; It is wrong to set the template parameter to int in this way ( Compile error: "Error C2079: ' A ' uses undefined class ' a<int> '), The class template parameter does not have an argument deduction problem. in other words, the integer value 2 cannot be deduced to be passed to the template parameter as int type. To set the class template parameter to int type, you must specify a<int> mas such.

4. The method for defining member functions outside the class template is:

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

For example, there are two template parameter T1, andT2 's class a has a void H () function, the syntax for defining the function is:

   Template<class t1,class t2> void A<t1,t2>::h () {}.

Note: When you define a member of a class outside of a class, the template parameters after the templates should match the template parameters of the class you are defining.

5. Note again: the declaration or definition of a template can only be done within a global, namespace, or class scope. That is, it cannot be done within a local scope, such as a template cannot be declared or defined in the main function.

Third, the formal parameters of the template

There are three types of template parameters: type parameters, non-type parameters, and template parameters.

1, type parameter

1.1. Type template parameter: The type parameter is composed of the closing word class or typename followed by specifier , such as template<class t> void H (t a) {}; t is a type parameter, and the name of the type parameter is self-determined by the user. 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.

    Author Original: 1.2, cannot specify two different types for the same template type parameter, such as template<class t>void H (t A, T b) {}, statement call H (2, 3.2) An error occurs because the statement specifies two types for the same template parameter T , the first argument 2 designates the template parameter T as int, and the second argument 3.2 the template parameter as double , the two types of parameters are inconsistent and error occurs. (for function templates)

Author Original: 1.2 The function template is correct, but the class template is ignored. The case of the class template is supplemented below.

    I added 1.2 supplemental version (for class template), when we declare the class object to be:a<int> A, such as Template<class t>t g (t A, T b) {}, The statement call A.G (2, 3.2) will compile without error, but there will be a warning because the class object is declared with the T converted to the int type, and the second argument 3.2 The template parameter is specified as a double, and at run time, the 3.2 is cast to 3. When we declare that the object of the class is:a<double> A, there is no such warning at this point, since an int to a double is an automatic type conversion.

Demo Example 1:

TemplateDemo.h

1 #ifndef template_demo_hxx 2 #define TEMPLATE_DEMO_HXX 3  4 Template<class t> class a{5     public:6         t g (t A,t b); 7         A (); 8}; 9 #endif

TemplateDemo.cpp

1 #include <iostream.h> 2 #include "TemplateDemo.h" 3  4 template<class t> a<t>::a () {} 5  6 Template<class t> t a<t>::g (t a,t b) {7     return a+b; 8} 9 void Main () {one     a<int> a;12     cout<<a.g (2,3.2) <<endl; 13}

Compilation Result:

1--------------------configuration:templatedemo-win32 Debug--------------------2 compiling ... 3 TEMPLATEDEMO.CPP4 g:\c++\cdaima\templatedemo\templatedemo.cpp: warning C4244: ' argument ': Conversion from ' Const double ' to ' int ', possible loss of data0 error (s), 1 warning (s)

  Run Result: 5

As we can see from the test example above, it's not as tight as the author's original! This is only the test results for me and others! Please the spirit of truth-seeking attitude, self-verification!

2, non-type parameters

2.1. Non-type template parameter: 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.2, the non-type parameter inside the template definition is a constant value, that is, the non-type parameter inside the template is a constant.

    2.3, non-type template parameters can only be integral type, pointers and references, such as double,string, String * * Such type is not allowed. but double &,double *, the object's reference or pointer is correct.

2.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.

2.5, note: any local object, local variables, the address of the local object, the address of the local variable is not a constant expression, can not be used as an argument for non-type template parameters. 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.

2.6, the address or reference of a global variable, the address of a global object, or a const-type variable is a constant expression that can be used as an argument for a non-type template parameter.

2.7. The result of thesizeof expression is a constant expression and can also be used as an argument for a non-type template parameter.

2.8. When the template's formal parameter is an integer, the argument must be an integral type when the template is called, and is constant during compilation, such as Template <class T, int a> class a{}; If there is an int B, then a<int, b> m; An error occurs because B is not a constant, if const int B, then a<int, b> m, is correct, because then b is a constant.

    2.9, non-type parameters generally should not be used in function templates , such as a function template template<class T, int a> void H (t b) {}, if using H (2) An error is invoked that cannot be performed on a parameter of the non-type parameter A, which can be resolved with a display template argument, such as using H<int, 3> (2) to set the non-type parameter A to an integer 3. The display template arguments are described later.

2.10. Conversions allowed between formal parameters and arguments for non-type template parameters
1. Allow conversion from array to pointer, from function to pointer. such as: Template <int *a> class a{}; int b[1]; A<b> m; that is, array-to-pointer conversion
2, 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 *.
3. Improve the conversion. such as: Template<int a> class a{}; const short b=2; A<b> m; That is, the ascending conversion from short to int
4, integer value conversion.   such as: template<unsigned int a> class a{}; A<3> m; That is, the conversion from int to unsigned int.
5, the general conversion.

Non-type Parameters demo Example 1:

  The size of the stack is specified by the user himself, and the related operations of the stack are implemented.

TemplateDemo.h

 1 #ifndef template_demo_hxx 2 #define TEMPLATE_DEMO_HXX 3 4 template<class T,int maxsize> class stack{//maxsize by user    Set your own 5 private:6 T Elems[maxsize] when creating an object;    An array containing elements of 7 int numelems;    The current total number of elements is 8 public:9 Stack ();    The constructor is a void push (T const&);        Pressed element one void pop ();    Pop-up elements of the T top () const; Returns the top element of the stack, bool empty () const{//return stack is empty, return numelems = = 0;15}16 bool Full ( ) const{//return stack is full and return numelems = = maxsize;18}19};20 template <class t,int maxsize&gt ; Stack<t,maxsize>::stack (): Numelems (0) {//initial stack does not contain element 23//Don't do anything.}25-template <class t,int maxsize& gt;27 void Stack<t, Maxsize>::p ush (T const& elem) {if (Numelems = = MAXSIZE) {$ throw Std::out_of_ra   Nge ("STACK&LT;&GT;::p ush (): Stack is full");}31 elems[numelems] = Elem;               Additional elements: ++numelems; IncreaseNumber of elements}34 template<class t,int maxsize>36 void Stack<t,maxsize>::p op () {PNS if (numelems <= 0) {38               Throw Std::out_of_range ("STACK&LT;&GT;::p op (): Empty Stack");}40--numelems; Reduce the number of elements in}42-template <class t,int maxsize>44 T stack<t,maxsize>::top () const{45 if (Numelems <=  0) {Std::out_of_range throw ("Stack<>::top (): Empty Stack"),}48 return elems[numelems-1]; Returns the last element}50 #endif

TemplateDemo.cpp

 1 #include <iostream.h> 2 #include <iostream> 3 #include <string> 4 #include <cstdlib> 5 #include  "TemplateDemo.h" 6 7 int main () {8 try {9 stack<int,20> int20stack;  A stack of 20 int elements can be stored stack<int,40> int40stack; A stack of 40 int elements can be stored stack<std::string,40> stringstack; Stacks that can store 40 string elements 12 13//Use stacks that can store 20 int elements Int20stack.push (7); Std::cout << Int20stack.    Top () << Std::endl; 716 Int20stack.pop (); 17 18//Use a stack that can store 40 strings ("Hello") stringstack.push    << stringstack.top () << Std::endl;    Hello21 Stringstack.pop ();    Stringstack.pop (); Exception:stack<&gt::p op<>: Empty stack23 return 0;24}25 catch (Std::exception const& ex  ) {Std::cerr << "Exception:" << ex.what () << std::endl;27 return exit_failure;   Exit program with Error flag 28  }29} 

Operation Result:

    

non-type parameters demo Example 2:

TemplateDemo01.h

Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code

TemplateDemo01.cpp

Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code

Run Result: 1

1 #include <iostream.h>2 #include "TemplateDemo01.h" 3 4 void Main () {5     comparedemo<double> cd;6     Cout<<cd.compare (3.2,3.1) <<endl;7}

 Run Result: 1

  TemplateDemo01.h changes are as follows:

1 #ifndef template_demo_o1 2 #define TEMPLATE_DEMO_01 3  4 Template<typename t> class comparedemo{5 public     : 6         int Compare (t&, t&); 7}; 8  9 template<typename t> int comparedemo<t>::compare (t& a,t& b) {One (a     ) >0) 12         return 1;13     else if ((a) <0)         return-1;15     else16         return 0;17}18 #endif

TempalteDemo01.cpp

1 #include <iostream.h>2 #include "TemplateDemo01.h" 3 4 void Main () {5     comparedemo<int> cd;6     int A =2,b=3;7     Cout<<cd.compare (A, b) <<endl;8}

non-type parameters demo Example 3:

TemplateDemo02.cpp

1 #include <iostream.h> 2  3 template<typename t> 4 const t& MAX (const t& a,const t& b) {5     R Eturn a>b? A:B; 6} 7  8 void Main () {9     Cout<<max (2.1,2.2) <<endl;//template arguments are implicitly deduced as Double10     cout<<max< Double> (2.1,2.2) <<endl;//displays the specified template parameters.     cout<<max<int> (2.1,2.2) <<endl;//displays the specified template parameter, which converts the function function directly to int. 12}

Operation Result:

       

cout<<max<int> (2.1,2.2) <<endl; Displays the specified template parameter, converting the function function directly to int. This statement will appear with a warning:


Warning C4244: ' argument ': Conversion from ' const double ' to ' const int ', possible loss of DATA6 7 templatedemo02.obj-0 Error (s), 2 warning (s)

C + + template (ii) "Go"

Related Article

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.