C + + Introductory Learning-templates

Source: Internet
Author: User
Tags float max

Why do I need a template?

We've learned about overloading (overloading), and for overloaded functions, C + + calls overloaded functions with proper matching of function arguments (number of arguments, parameter types). 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.

function 1int max (int x, int y); {return (x>y)? X:y;} function 2float max (float x, float y) {return (x>y) x:y;} function 3double max (double x, double y) {return (c>y) x:y;}

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 errors caused by the incomplete definition of overloaded functions (for example, we define a char, a, and b; Then the program will go wrong when you execute Max (A, B) because we do not have an overloaded version of the char type defined.


Similarly, for classes, the same problem exists (basically repetitive work):

Compares two integers to a class compare_int{public:compare (int a,int b) {x=a;y=b;} int Max () {return (x>y) x:y;} int min () {return (x<y) x:y;} Private:int x,y;};/ /Compare two floating-point numbers with class Compare_float{public:compare (float a,float b) {x=a;y=b;} Float Max () {return (x>y) x:y;} Float min () {return (x<y) x:y;} Private:float x, y;}


To solve the above problems, C + + introduces template mechanism: template is a tool to implement code reuse mechanism, it can implement type parameterization, that is, the type is defined as parameters, thus realizing the real code reusability . Template can be divided into two categories, one is a function template , the other is a class template .


function Templates

The general form of a function template is as follows:

template <class parameter name, class parameter name, ......> return type function name (formal parameter list)

{

function definition Body

}

Where template and class are keywords, class can be replaced with TypeName, where TypeName and class are not distinguished,<> the parameters in parentheses are called template parameter, template parameter and function parameter are similar, template parameter cannot be empty.


Once you declare a class template, you can declare it using a template parameter name where 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.

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 parameter T in the swap of the template function is replaced by int, and the template function becomes swap (int &a, int & AMP;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 implements the type-independent code that implements the function.

The sample code is as follows:

#include <iostream>using std::cout;using std::endl;//declares 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 substituted by any letter or number. Template <typename t>template <class t> t max (t x,t y) {return (x>y)? X:y;} int main () {    int a=2, b=10;    cout<< "larger integers:" <<max (A, b) <<endl;double m=1.5, n=5.6;    cout<< "Larger real number:" <<max (M, N) <<endl;return 0;}


The results of the operation are as follows:


class Template

The general form of a class template is as follows:

template <class parameter name, class parameter name, ......> class name
{

Class definition ...

};


Once you declare a class template, you can use the formal parameters of a class template to name member variables and member functions in a class, that is, where you can use a built-in type in a class, you can use a template parameter name to declare it. For example:

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

In Class A, two member variables A and B are declared with type T, and a return type of T with two parameter type T is also declared Hy.


class Template Object creation: For example a template class A, the method of creating an object using a class template 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.


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

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


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

Template<class T1, Class t2> class a{public:void H ();}; Template<class t1,class t2> void A<t1,t2>::h () {//...}


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.


The sample code is as follows:

 #include <iostream>using namespace Std;template <class numtype> class Compare//class Template {Public://compare (numtype A,numtype b) {x=a;y=b;} Compare (Numtype a,numtype b); Numtype Max () {return (x>y) x:y;} Numtype min () {return (x<y)? X:y;} Private:numtype x, y;}; Template <class numtype> compare<numtype>::compare (numtype a,numtype b) {x=a;y=b;}  int main () {COMPARE<INT>CMP1 (3,7);//define Object CMP1 For comparison of two integers cout << cmp1.max () << "is the Maximum" << Endl;cout << cmp1.min () << "is the Minimum" << Endl << Endl; Compare<float> CMP2 (45.78,93.6); Define object CMP2 For comparison of two floating-point numbers cout << Cmp2.max () << "is the Maximum" <<endl;cout << cmp2.min () << " Is the Minimum "<<endl<<endl; Compare<char> Cmp3 (' A ', ' a '); Define object Cmp3, for comparison of two characters cout << Cmp3.max () << "is the Maximum" <<endl;cout << cmp3.min () << "I s the Minimum "<<endl;return 0;} 

The results of the operation are as follows:



For this tutorial sample code download please click here.


Resources:

http://www.cnblogs.com/gw811

Http://www.cnblogs.com/gaojun

C + + Introductory Learning-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.