Function templates and class templates in C ++

Source: Internet
Author: User

Because templates can be usedProgramSet up function libraries and class libraries with common types. The template is also a tool supporting parameterized polymorphism in C ++.

Function Template

Function templates can use the same programCodeThe key to processing different types of data is to describe the processed data type as a parameter, that is, type parameterization.

The general form of defining a function template is:

Template <class type parameter name 1, class type parameter name 2,...>
Function return value type function name (table of parameters)
{
Function body
}

Note:

(1) Here, the type parameter name is a common parameter name that represents all types of data. It can represent the basic data type or the class.

(2) the method for writing a function template is:

Step 1: define a common function. The data type uses a specific common data type. For example, the print array is used as an example. First, define a common function that prints an integer array:

Void printarray (int * array, int count)

{

For (INT I = 0; I <count; I ++)

Cout <array [I] <"";

Cout <Endl;

}

Step 2: parameterize data types: replace all specific data type names (such as INT) with abstract type parameter names (such as t) defined by yourself ).

Step 3: Use the keyword template to declare the type parameter name before the function header. In this way, a specific function is transformed into a general function template:
Template <class T> void printarray (T * array, int count)
{
For (INT I = 0; I <count; I ++)
Cout <array [I] <"";
}

(3) A function template is not an executable function. It only describes the function program and does not generate Execution Code for the compiled program.

(4) When the Compilation Program encounters a function call:

When the function name (real parameter table) is used, the specific data type in the real parameter table is automatically replaced with the type parameter in the function template to generate an implicit overload function, the program code of this overload function is the same as the function template, and the type uses the specific data type in the real parameter table. For example, when the program displays the function call statement printarray (A, acount, the compiler will replace all t in the function template with the specific data type int Based on the Data Type int of the first real parameter, this produces a specific definition of the executable function (this process is called template instantiation ):

Void printarray (int * array, int count );

Template Functions

A function template is a description of a group of functions. It is not a real function, and the compilation system does not generate any Execution Code. When the compilation system finds a function call that matches the function template in the program, an overload function is generated. The function body of the overload function is the same as that of the function template. This overload function is calledTemplate Functions.

 

Class Template

Concept of class template: Lists A linked list class to discuss the necessity of class template introduction. The following list class is a linked list class, nested with a node structure type. The specific definition is as follows:

 Class  List {  //  Define linked list  Public  : List ();  //  Declare Constructors      Void Add ( Int &);//  Declare member functions for adding nodes      Void Remove ( Int &); //  Declare member functions for deleting nodes      Int * Find ( Int &); //  Declare the member functions of the search Node      Void Printlist (); //  Declare member functions of the printed linked list ~ List (); // Declare destructor  Protected  :  Struct  Node {  //  Define the structure type of a node Node * pnext; //  Pointer member pointing to the next node          Int * PT; //  Pointer member pointing to the current node data  }}; 

The data type of the linked list node is int type. To make the data of the node in the linked list belong to other types (such as char and double type), you must redefine the Linked List class, because these classes only have different types of data on nodes, and the rest of the code is identical, a large number of code duplication occurs. Create a universal linked list template for the Linked List class family to minimize program code redundancy. Replace the data type in the List class with a common parameter T, as shown below:

Template < Class T> Class  List {  //  Define a general linked list template  Public  : List ();  //  Declare Constructors      Void Add (T &); //  Declare member functions for adding nodes     Void Remove (T &); //  Declare member functions for deleting nodes T * Find (T &); //  Declare the member functions of the search Node      Void Printlist (); //  Declare member functions of the printed linked list ~ List (); //  Declare destructor  Protected  :  Struct Node { // Define the structure type of a node Node * pnext; //  Pointer member pointing to the next node T * PT; //  Pointer member pointing to the current node data  };}; 

This class template uses the parameter type T, which is used in the description of member functions add (), remove (), find (), and struct definition. In fact, a class template describes a group of classes. It can be seen that the introduction of class templates is also a way to reduce repeated programmer labor and overcome program redundancy.

Like a function template, you can use a class template to define a mode for the class, so that some data members in the class, some member function parameters, and the return values of some member functions can take any type. A class template is an abstraction of a group of classes with different data types. A programmer only needs to create a class template for the entire class family composed of these classes and provide a set of program code, can be used to generate a variety of specific classes (this type can be considered as an instance of the class template), thus greatly improving the programming efficiency.

The general form of the definition class template is:

Template <type name parameter name 1, type name parameter name 2,...>ClassClass Name {class declaration body}; for example, template<ClassT>ClassSmemory {...Public:VoidMput (t x );...}

Defines a class template named smemory with the type parameter T.

The general form of the class member functions defined externally in the class template is:

Template <type name parameter name 1, type name parameter name 2,...>Function return value type Class Name<Parameter name1Parameter Name2,...>: Member function name (parameter table) {function body} example: Template<ClassT>VoidSmemory <t>: Mput (t x ){...}

It refers to the member function that defines a class template smemory. The function name is mput, the type of the form parameter X is t, and the function has no return value.

A class template is an abstraction of a class family. It only describes a class. A compiled program does not create program code for a class template (including member function definitions, however, by instantiating a class template, you can generate a specific class and its objects.

Unlike function templates:Function template instantiation is automatically completed by the compiler when processing function calls, and class template instantiation must be explicitly specified by the programmer in the program,

The general format of its instantiation is:

Class Name <data type 1 (or data), data type 2 (or data)…> Object Name

For example, smemory <int> mol; replace all the type parameter t of the class template smemory with int type to create a specific class and generate an object mol for the specific class.

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.