Detailed knowledge of class templates in C + + programming _c language

Source: Internet
Author: User
Tags comparison float max integer numbers

Sometimes, there are two or more classes that have the same functionality, just different data types, as the following statement declares a class:

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

The effect is to compare two integers by calling the member function max and Min to get the large and small number of two integers.

If you want to compare two floating-point numbers (float), you need to declare a different class:

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;

Obviously this is essentially repetitive and there should be a way to reduce duplication of work.

C + + has increased the functionality of the template (template) in the later stages of development, providing a way to solve such problems. You can declare a generic class template that can have one or more virtual type parameters, such as the following class template can be synthesized from the above two classes:

Template <class numtype>//Declare a template with a virtual type named Numtype class Compare//
class template named Compare
{public
:
  Compare (numtype a,numtype b)
  {
   x=a;y=b;
  }
  Numtype Max ()
  {return
   (x>y)? x:y;
  }
  Numtype min ()
  {return
   (x<y)? x:y;
  }
Private:
  numtype x,y;

Compare this type of template with the first Compare_int class before you see two different.

1 Add a row when declaring a class template

  Template <class type parameter name >


Template means "template", which is a keyword that must be written when declaring a class template. The contents of the angle brackets behind the template are the parameter table columns for the template, and the keyword class indicates the type parameters. In this case, Numtype is the name of a type parameter. This name can be taken arbitrarily, as long as it is a valid identifier. Taking numtype here just means "data type". At this point, Mimtype is not an actual type name that already exists, it is just a virtual type parameter name. will be replaced by an actual type name in the future.

2 the original type name int is replaced by the virtual type parameter name Numtype.
When a class object is established, if the actual type is specified as an int, the compiler replaces all the numtype with an int and, if specified as a float, replaces all numtype with float. This will enable "a class of multiple uses".

Because the class template contains type parameters, it is also called a parameterized class. If a class is an abstraction of an object and an object is an instance of a class, the class template is an abstraction of the class, which is an instance of the class template. Class templates allow you to build classes that contain a variety of data types.

So, when you declare a class template, how do you use it? How to make it into an actual class?

Let's review the method of defining objects using classes:

  Compare_int CMP1 (4,7); Compare_int is a declared class


The effect is to create an object of the Compare_int class and assign arguments 4 and 7 to formal parameters A and B, respectively, as two integers for comparison.

The method of defining objects with a class template is similar, but cannot be written directly

  Compare CMP (4,7); Compare is the class template name

Compare is a class template name, not a specific class, and the type Numtype in the class template body is not an actual type, but a virtual type that cannot be used to define objects. You must replace the virtual type with the actual type name, specifically:

  Compare <int> CMP (4,7);


That is, the actual type name is specified within the angle brackets after the class template name, and when compiling, the compiler uses int instead of the type parameter Numtype in the class template, which materializes the class template or instantiates it. Then compare<int> is equivalent to the Compare_int class described earlier.

[Example] declares a class template that uses it to achieve a comparison of two integers, floating-point numbers, and characters to find large and decimal numbers.

#include <iostream> using namespace std;
  Template <class numtype>//define class template class Compare {public:compare (numtype A,numtype b) {x=a;y=b;}
  Numtype Max () {return (x>y)? X:y;}
  Numtype min () {return (x<y)? X:y;}
Private:numtype X,y;
}; int main () {compare<int > Cmp1 (3,7);//define Object CMP1, for comparison of two integers Cout<<cmp1.max () << "is" Maximum of T Wo integer numbers. "
  <<endl; Cout<<cmp1.min () << "is the Minimum of two integer numbers."
  <<endl<<endl; Compare<float > Cmp2 (45.78,93.6); Defines the object CMP2, which is used for comparison of two floating-point numbers Cout<<cmp2.max () << "is the Maximum of two float numbers."
  <<endl; Cout<<cmp2.min () << "is the Minimum of two float numbers."
  <<endl<<endl; Compare<char> Cmp3 (′a′,′a′); Defines the object Cmp3, which is used for the comparison of two characters Cout<<cmp3.max () << "is" the Maximum of two characters. "
  <<endl; Cout<<cmp3.min () << "is the Minimum of two characters."
<<endl;  return 0;
 }

The results of the operation are as follows:

7 is the Maximum of two integers.
3 is the Minimum of two integers.

93.6 is the Maximum of two float numbers.
45.78 is the Minimum of two float numbers.

A is the Maximum of two characters.
A is the Minimum of two characters.

Another problem to note is that the member functions in the class template listed above are defined within the class template. If defined outside the class template, you cannot use a generic definition of a class member function:

 Numtype Compare::max () {...}//cannot define member functions in a class template

Instead, it should be written in the form of a class template:

  Template <class numtype>
  numtype Compare<numtype>::max ()
  {return
    (x>y)? x:y;
  }

The first line above represents the class template, and the second left side of the Numtype is the virtual type name, followed by compare <numtype> is a whole and a class with parameters. Indicates that the MAX function defined is within the scope of the class compare <numtype>. When you define an object, the user, of course, specifies the actual type (such as int), and when compiled, the virtual type name Numtype in the class template is replaced by the actual type. So compare <numtype > is equivalent to an actual class. You can rewrite the example to define the member functions outside the class template.

By summarizing the above introductions, you can declare and use class templates like this:
1 Write a real class first. Because of its semantic clarity, the meaning is clear, generally not error.

2 Use a specified virtual type name (for example, numtype in the previous example) to change the name of the type that is being changed in this class (for example, if int is to be changed to float or char).

3 Add a line before the class declaration, in the form:

Template <class Virtual type parameters >

Such as:

  Template <class numtype>//Note No semicolon
  class Compare
  {...};//Class body

4 Use the following form when defining an object with a class template:

  Class template name < actual type name > object name;
  Class template name < actual type name > object name (Argument table column);


Such as:

  Compare<int> CMP;
  Compare<int> CMP (3,7);

5 If you define a member function outside of a class template, you should write it as a class template:

  Template <class Virtual type parameters >
  function type class template name < virtual type parameter:: member function name (function parameter list column) {...}


A few notes on the class template:
1 class template can have one or more type parameters, each type must precede the class, such as:

  Template <class t1,class t2>
  class SomeClass
  {...};


When you define an object, you substitute the actual type name, such as:

  Someclass<int,double> obj;

2 As with classes, use a class template to be aware of its scope and to define objects only within its valid scope.

3 templates can have layers, and a class template can be used as a base class to derive derived template classes. The practical application of this knowledge is less, this tutorial is not introduced, interested students can learn by themselves.

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.