C++ class template details and examples

  • 2020-04-02 01:50:36
  • OfStack

Function templates in C++

The same is true for class declarations. Sometimes, there are two or more classes with the same functionality but different data types, such as the following statement declaring 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;
};

Its purpose is to compare two integers. You can get the big and the small of the two integers by calling the function members Max and min.

If you want to compare two floats, declare another 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 basically repetitive work and there should be ways to reduce repetitive work. Class templates in C++ were added for this type of problem.

You can declare a generic class template that has one or more type parameters for virtual functions,


class Compare
{
 public:
  Compare(T a,T b)
  {
   x=a;
   y=b;
  }
  T max()
  {
   return(x>y)?x:y;
  }
  T min()
  {
   return(x<y)?x:y;
  }
 private:
  T x,y;
}; 

Comparing this type of template to the first Compare_int class, you can see two differences:
(1)

When declaring a class template, add a line, template < Class type parameter name >

Template means "template" and is a keyword that must be written when declaring a class template. The contents in the Angle brackets after the template are the parameter table columns of the template, and the keyword class indicates that the type parameter is following. In this case, T is a type parameter name, which is arbitrary, as long as it is a valid identifier.

T is not an existing actual type name, it is just a dummy type parameter name that will be replaced by an actual type name in the future.

(2)

Replace the original type name int with the dummy type parameter name T. When creating a class object, the compiler replaces all T's with int if the actual type is specified as int, and all T's with float if specified as float. This can achieve "a kind of multi-purpose."

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, then a class template is an abstraction of a class and a class is an instance of a class template. Class templates can be used to create classes with various data types.

So, after we declare a class template, how do we use it?

General way to define objects with classes:

Compare_int cmp1 (4, 7);             //Compare_int is a declared class


It creates an object cmp1 of the Compare_int class and assigns arguments 4 and 7 to parameters a and b, respectively, as two integers to compare.

Objects are defined similarly with class templates, but not directly

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

Compare is the name of the class template, not a concrete class. The type T in the body of the class template is not an actual type, but a virtual type, which cannot be used to define objects. The virtual type must be replaced by the actual type name.

The Compare < int > Cmp1 (4, 7);

The actual type name is specified in Angle brackets after the class template name. At compile time, the compilation system replaces the type parameter T in the class template with an int, thus externalizing, or instantiating, the class template.

Then Compare < int > This is equivalent to the Compare_int class described earlier.

==================== == sample code 1.1==================== =====

Declaration of a class template, using it to achieve the comparison of two integers, floating point, and characters, to find large Numbers and decimals


#include<iostream>
using namespace std;
template<class T>   //Declares a class template with the virtual type T
class Compare
{
 public:
  Compare(T a,T b)
  {
   x=a;
   y=b;
  }
  T max()
  {
   return(x>y)?x:y;
  }
  T min()
  {
   return(x<y)?x:y;
  }
 private:
  T x,y;
}; 
int main()
{
 Compare <int> cmp1(3,7);  //Defines the object cmp1 for comparing two integers
 cout<<"Max : "<<cmp1.max()<<endl;
 cout<<"Min : "<<cmp1.min()<<endl<<endl;
  Compare <float> cmp2(45.89,88.76);//Defines the object cmp2 for comparing two floating point Numbers
 cout<<"Max : "<<cmp2.max()<<endl;
 cout<<"Min : "<<cmp2.min()<<endl;
 Compare <char> cmp3('a','A'); //Defines the object cmp3 for the comparison of two characters
 cout<<"Max : "<<cmp3.max()<<endl;
 cout<<"Min : "<<cmp3.min()<<endl;
 return 0; 
}
Operation results:
< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201310/20130908221740437.png ">

One more thing to note: the member functions in the class template listed above are defined within the class template.

If it is defined outside the class template, it cannot be defined as a class member function:

T compare: Max () {... }                         // you cannot define a member function in a class template like this

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


template<class T>
T Compare <T> ::max()
{
    return(x>y)?x:y;
}

The first line declares the class template, the T on the left side of the second line is the name of the virtual type, and then Compare < T > It's a whole, it's a class with arguments. Means that the Max function defined is in the class Compare < T > Of the scope of.

When defining an object, of course, the user specifies the actual type (figure int), and at compile time the virtual type name T in the class template is replaced by the actual type. So the Compare < T > It's an actual class.

Summarize the problems to be paid attention to when using:

(1) add a line before the class declaration in the format of

The template < Class virtual type parameter >

Such as:


template<class T>   //Note that there is no semicolon at the end of the line
class Compare
{
 ... 
}

(2) when defining objects with class templates, the following forms are used:

Class template name < Actual type name > Object name;

Class template name < Actual type name > Object name (argument list);

Such as:


Compare <float> cmp2(45.89,88.76);//Defines the object cmp2 for comparing two floating point Numbers

(3) if a member function is defined outside the class template, it should be written in the form of the class template:

The template < The class   Virtual type parameter >

Function types       Class template name < Virtual type parameter > :: member function name (function parameter list column){...... }

(4) the type parameters of the class template can have one or more, each type must be preceded by a class, such as:


template <class T1,class T2>
class someclass
{ ... } ; 

When defining an object, enter the actual type name, such as

someclass<int,double> obj;

(5) as with classes, class templates should be scoped, and can only be used to define objects within their valid scope.

If the class template is defined at the beginning of the A file, the scope of the A file is valid and you can use the class template anywhere, but you cannot use the class template to define objects in the B file.

(6) templates can have levels, a class template can be used as a base class, derived from derived classes.


Related articles: