C ++ template (1): Template

Source: Internet
Author: User
Tags float max

C ++ template (1): Template

1.Template concept.

We have learnedOverloading)For overloaded functions, the C ++ check mechanism can be implemented through different function parameters and different classes. Call the overload function correctly. For example, to obtain the maximum values of two numbers, we define the MAX () function to define different data types.Overload)Version.

// 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 ;}

However, if char a and B are defined in the main function, an error occurs when max (a, B) is executed, because we do not define the overloaded version of the char type.

Now, let's re-examine the above max () functions. They all have the same function, that is, to find the maximum value of two numbers. Can we write only one set of code to solve this problem? This will avoid calling errors caused by incomplete definition of overload functions. To solve these problems, C ++ introduces a template mechanism,Template definition: A template is a tool for implementing the code reuse mechanism. It can implement type parameterization, that is, define the type as a parameter, thus realizing real code reusability. Templates can be divided into two types: function templates and class templates.

2.Function template writing

The function template is generally in the following format:

Template <ClassOr you can useTypenameT>

Return type function name (parameter table)
{// Function Definition body}

Description: template is a keyword used to declare a template. It indicates that the class that declares a template keyword cannot be omitted. If the type parameter is redundant, class <type parameter table> must be added before each parameter. It can contain basic data types and class types.

 

See the following program:

// Test. cpp # include <iostream> using std: cout; using std: endl; // declare a function template to compare the input values of two parameters of the same data type, class can also be replaced by typename, and // T can be replaced by any letter or number. Template <class T> T min (T x, T y) {return (x <y )? X: y;} void main () {int n1 = 2, n2 = 10; double d1 = 1.5, d2 = 5.6; cout <"small integer: "<min (n1, n2) <endl; cout <" smaller real number: "<min (d1, d2) <endl; system ("PAUSE ");}

 

Program running result:

 

 

Program analysis: the main () function defines two integer variables n1 and n2, d1 and d2, and then calls min (n1, n2 ); that is, the instantiation function template T min (T x, T y) where T is int type, find the minimum value in n1, n2. similarly, when min (d1, d2) is called, the minimum value in d1 and d2 is obtained.

3.Class template writing

Define a class template:

Template <ClassOr you can useTypenameT>
Class name {
// Class definition ......
};

Note: "template" declares the keywords of each template, indicating that a template can be declared. The template parameter can be either a template or multiple templates.

For example, define a class template:

// ClassTemplate. h # ifndef ClassTemplate_HH # define ClassTemplate_HHtemplate <typename T1, typename T2> class myClass {private: T1 I; T2 J; public: myClass (T1 a, T2 B ); // Constructor void show () ;}; // This is the Constructor // note the formats of template <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> void myClass <T1, T2 >:: show () {cout <"I =" <I <", J = "<J <endl ;}# endif // Test. cpp # include <iostream> # include "ClassTemplate. h "using std: cout; using std: endl; void main () {myClass <int, int> class1 (3,5); class1.show (); myClass <int, char> class2 (3, 'A'); class2.show (); myClass <double, int> class3 (2.9, 10); class3.show (); system ("PAUSE ");}

 

4. Non-type template parameters

Generally, a non-type template parameter can be a constant INTEGER (including enumeration) or a pointer to an external linked object.

That is to say, floating point numbers cannot be used, and pointers to internal linked objects cannot be used.


template<typename T, int MAXSIZE>class Stack{Private:       T elems[MAXSIZE];…}; int main(){       Stack<int, 20> int20Stack;       Stack<int, 40> int40Stack;…};

 

5. Use the template type

Sometimes the template type is a container or class. To use the type under this type, you can call it directly. The following is a template function that can print the sequence and chain of containers in STL.

template <typename T>void print(T v){ T::iterator itor; for (itor = v.begin(); itor != v.end(); ++itor) {  cout << *itor << " "; } cout << endl;}void main(int argc, char **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 conversion for Type Derivation
Before determining the template parameter type, the compiler performs the following implicit type conversion:

Left value transformation
Modifier Conversion
Conversion from a derived class to a base class

See C ++ Primer ([NOTE 2], P500.

In short, the compiler weakens some type attributes, such as the left Value Attribute of the reference type in our example. For example, the compiler instantiates a function template with a value type instead of a reference type.

Similarly, it uses the pointer type to instantiate the function template, rather than the corresponding array type.

It removes the const modifier and never uses the const type to instantiate the function template. It always uses the corresponding non-const type, but for pointers, the pointer and const pointer are different types.

Bottom line: Automatic template parameter derivation includes type conversion, and some type attributes will be lost when the compiler determines the template parameters automatically. These types of attributes can be retained when explicit function template parameter declarations are used.

 

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

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.