Templates in C ++ (Templates)

zhaozj2021-02-08  201

Author: Miao Xin Dong

What is a template?

The template is based on the parameter type generated function and the mechanism (sometimes referred to as "parameter determination type"). By using a template, you can only design a class to handle multiple types of data without having to create classes for each type.

For example, create a type of security function to return a smaller one in two parameters. If you do not use Templates, you must write a series of functions:

// min for ints

INT min (int A, int b)

RETURN (a

// min for longs

Long min (long a, long b)

RETURN (a

// min for chars

Char min (Char A, Char B)

RETURN (a

// ETC ...

Using Templates, you can reduce the repeating section to form a function:

Template T MIN (T A, T B)

RETURN (a

The template can reduce the amount of source code and increase the mobile phone without reducing type security.

When to use templates

Templates are often used to achieve the following functions:

Ø Create a type of secure set class (for example, stack) to process various types of data

Ø Add additional type checks to the function to avoid empty pointers

Ø Merge operator reload group to modify type behavior (such as smart pointer Smart Pointer)

Most applications can be implemented without templates; however, templates have the following advantages:

Ø It is easy to develop. You can create a normal version only for your class or function instead manually created special circumstances.

Ø It is easy to understand. The template provides a straightforward approach for abstract type information.

Ø Type safety. The type used by the template is clear when compiling, the compiler can check the type before an error occurs.

Function Templates

Using the function template, you can specify a set of functions based on the same code but handle different types or classes, for example:

Template Void MySwap (T & A, T & B)

{

T c (a);

A = B; b = C;

}

This code defines a function family to exchange the parameter value of the function. From this template you can generate a series of functions, not only swap integer, long integer, but also swap user-defined types, if the constructor and assignment operators are properly defined, the MySWAP function can even exchange classes.

In addition, the function template prevents you from exchanging different types of objects because the compiler knows the type of parameters A and B when compiling.

You can call a function template function like calling a normal function; there is no special syntax. E.g:

INT I, J;

CHAR K;

MySWAP (i, j); // ok

MYSWAP (i, k); // error, Different Types.

You can make an external description for the Template parameters of the function template, for example:

Template void f (t) {...}

Void g (char J) {

F (j); // generate the specialization f (int)

}

When the Template parameter is described outside, the normal fixed type conversion will convert the parameters of the function as the corresponding function template parameter. In the above example, the compiler converts (CHAR J) to the Class Templates.

You can use class templates to create class families for one type.

Template Class Tempclass

{

PUBLIC:

TempClass (void);

~ Tempclass (void);

INT MEMBERSET (T A, INT B);

Private:

T tarray [i];

Int archsize;

}

In this example, the template class uses two parameters, a type T and an integer i, T parameter can pass a type, including structures and classes, the i parameter must pass the first integer, because i is a constant when compiling You can use a standard array declaration to define an array of members for I.

Template and macro comparison (Templates vs. macros)

In many ways, templates are similar to pretreatment macros, replacing the variables of the template with a given type. However, templates and macros have great difference:

Macro:

#define min (i, j) ((i) <(j))? (i): (j))

template:

Template t min (t i, t j) {RETURN ((i

Use the macro will bring the following questions:

Ø The compiler has no way to check if the type of the macro is consistent. A specific type of check is missing in the definition of the macro.

Ø Parameters i and j were called 2 times. For example, if any parameter has an increment, the increment will be added twice.

Ø Because the macro is compiled, the compiler error message will point to the macro of the compilation, not the macro definition itself. Moreover, the compilation phase macros will be revealed in the compilation table.

Comparison of templates and empty poins (Templates vs. void Pointers)

Many functions implemented with empty pointers can now be implemented with templates. Empty pointers are often used to allow functions to handle data of unknown types. When using an empty pointer, the compiler cannot distinguish classes, so you cannot handle the type check or type behavior such as using this type of operator, operator overload or constructors.

With templates, you can create functions and classes that handle specific types of data. Types look abstract in template definitions. However, a separate version of this function is created for each specified type of compiler. This makes the compiler can use classes and functions as they are using the specified type. The template can also make the code more concise because you don't have to create a special program for the type of structure, such as the type of structure.

Templates and collection classes (Templates and Collection Classes)

Templates are a good way to implement a collection class. The fourth edition and higher version of Microsoft Foundation Class Library uses templates to implement six collection classes: Carray, CMAP, CLIST, CTYPTRARRAY, CTYPTRLIST, and CTYPTRMAP.

MyStack Collection Class is a simple stack implementation. Here are two template parameters, T and I, specify the maximum value of the element type and the number of items in the stack in the stack. Push and POP member functions add and delete items in the stack and increase at the bottom of the stack.

Template Class MyStack

{

T stackbuffer [i];

INT CITEMS;

PUBLIC:

Void MyStack (Void): CItems (i) {};

Void Push; T POP (Void);

}

Template Void MyStack :: Push (Const T Item)

{

IF (CItems> 0)

StackBuffer [- CItems] = Item;

Else

Throw "stack overflow error."

Return;

}

Template t mystack :: POP (void)

{

IF (CItems

Return StackBuffer [CITEMS ]

Else

Throw "stack underflow error."

}

Templates and intelligent pointers (Templates and Smart Pointers)

C allows you to create a "Smart Pointer" class capsule and overload pointer operators to add new features for pointer operations. Templates allow you to create normal packages to enclose almost all types of pointers.

The following code summarizes a simple counting garbage collector reference. Template PTR implements a garbage collection pointer to any class inherited from Refcount.

#include

#define TRACE PRINTF

Class Refcount {

int CREFS;

PUBLIC:

Refcount (void) {crefs = 0;}

~ Refcount () {trace ("Goodbye (% D) / N", CREFS);}

Void UpCount (Void) { Crefs; Trace ("UP TO% D / N", CREFS;

Void Downcount (Void)

{

IF (--crefs == 0)

{

DELETE THIS;

}

Else

Trace ("DOWNTO% D / N", CREFS;

}

}

Class sample: public refcount {

PUBLIC:

Void Dosomething (void) {trace ("DID Something / N");

}

Template Class Ptr {

T * P;

PUBLIC:

PTR (t * p_): p (p_) {p-> UpCount ();

~ PTR (void) {p-> downcount ();

Operator t * (void) {Return P;

T & Operator * (void) {return * p;}

T * Operator -> (void) {RETURN P;}

Ptr & Operator = (PTR & P_)

{RETURN OPERATOR = ((t *) p_);}

PTR & Operator = (T * p_) {

P-> DownCount (); p = p_; p-> UpCount (); return * this;

}

}

Int main () {

PTR P = New Sample; // Sample # 1

Ptr P2 = New Sample; // Sample # 2

P = P2; // # 1 Will Have 0 Crefs, SO IT IS DESTROYED;

// # 2 Will Have 2 crefs.p-> dosomething ();

Return 0;

// AS P2 and P Go Out of Scope, Their Destructors Call

// DownCount. The cref variable of # 2 Goes to 0, SO # 2 IS

// destroyed

}

Class REFCOUNT and PTR provide a simple garbage collection solution for each instance that is inherited from Refcount. Note that using a parameter class such as PTR instead of multiple general classes such as PTR, the main benefit of PTR is that this form is a complete type. The previous code guarantees that PTR can be used in almost any T * used; in contrast, a common class PTR can only provide a VOID * inherent conversion.

For example, consider a class, symbol, string, etc. used to create and process file garbage collection. Depending on the class template PTR , the compiler can create template PTR , PTR , PTR , etc., and their member functions: PTR :: ~ PTR (), PTR < File> :: operator file * (), ptring> :: ~ ptr (), PTR :: operator string * (), etc.

转载请注明原文地址:https://www.9cbs.com/read-2381.html

New Post(0)