Important features of C ++-templates

Source: Internet
Author: User

Although template is very important, what is the relationship between it and "Using MFC? Yes! Chapter 2 when we design the scribble program, we need to use the collection classes of MFC, the template version has been available for this group of classes since MFC 3.0 (because visual c ++ compiler supports C ++ template since version 2.0 ). Before using it, we should always understand the new syntax, spirit, and application.

What is a template? How important? Kaare Christian wrote an article on PC-magazine at, which says:

It is not just because of genetic engineering, but also a long history of action for programmers. In the past, we used a simple and basic tool, that is, a text editor, to reproduce our program code. Today, C ++ provides us with a better breeding method template. One of the most common reasons for copying a piece of existing program code is to change the data type. For example, suppose you have written a plot function using the integer x and y coordinates. Suddenly you need the same program code, but the coordinate value is changed to long. Of course, you can use a text editor to copy the code and change the data type. With C ++, you can even use the overloaded function, so you can still use the same function name. The multiload of functions does make us have refreshing program code, but they mean you still have
Maintain identical algorithms in many parts of your program. The C language answers this question by using macros. Although you only need to write program code once for the same algorithm, macros have their own shortcomings. First, it is only applicable to simple functions. The second disadvantage is serious: macros do not provide data type tests, so they sacrifice a major benefit of C ++. The third disadvantage is that a macro is not a function. Any place in the program that calls a macro will be inserted by the source code of the Preprocessor of the compiler, instead of just a function call, therefore, every time you use a macro, your execution file will expand a little. Templates provides a better solution, which differentiates general algorithms from their material-type implementations. You can first write the program code of the algorithm, and then fill in the actual data type for later use. The new C ++ syntax also displays the data type as a parameter. With the template, you can have the advantage of the macro "write only once" and the advantage of the Multi-load function "type check.

There are two types of C ++ templates, one for function and the other for class.

Template Functions

Template <class T>
T power (T base, int exponent );
0001 template <class T>
0002 t power (T base, int exponent)
0003 {
0004 t result = base;
0005 if (exponent = 0) Return (t) 1;
0006 if (exponent <0) Return (t) 0;
0007 while (-- exponent) Result * = base;
Such a function declaration starts with a special template prefix, followed by a parameter column (in this example, only one parameter ). What is confusing is the word "class", which does not necessarily represent the class of C ++. It can also be a common data type. <Class T> only indicates that T is a type, which is provided only when this function is called.
The following is the template version of the power function:

#0001 template <class T>
#0002 t power (T base, int exponent)
#0003 {
#0004 t result = base;
#0005 if (exponent = 0) Return (t) 1;
#0006 if (exponent <0) Return (t) 0;
#0007 while (-- exponent) Result * = base;
#0008 return result;
#0009}
Doctrine: The above is the template version of the power function: the return value must be t of the type to match the declaration of the template function.

The following describes how to call the template function.

#0001 # include <iostream. h>
#0002 void main ()
#0003 {
#0004 int I = power (5, 4 );
#0005 long l = power (1000l, 3 );
#0006 Long Double D = power (Long Double) 1e5, 2 );
#0007
#0008 cout <"I =" <I <Endl;
#0009 cout <"L =" <L <Endl;
#0010 cout <"d =" <D <Endl;
#0011}
The execution result is as follows:
I = 625.
L = 1000000000
D = 1E + 010
In the first call, t becomes int, and in the second call, t becomes long. In the third call, t becomes a long double. However, if the data type is disordered during the call, such as int I = power (1000l, 4); // The base value is a long value, but the return value is an int. Error example! An error occurs during compilation.
How many types can the data type parameter t of the template function be used? I would like to say that almost "any data type" is acceptable, but any operation of this type of value in a function must be supported -- otherwise the compiler will not know what to do. Taking the power function as an example, it performs the following operations on the result and base values:
1. t result = base;
2. Return (t) 1;
3. Return (t) 0;
4. Result * = base;
5. Return result;
All built-in data types such as int and long in C ++ support the preceding operation. However, if you generate a power function for a c ++ category, the C ++ category must contain an appropriate member function to support the above actions. If you want to replace Class T with the c ++ class in the template function, you must know which operation actions have been used in this function, then you can implement them in your c ++ class. Otherwise, the error is intriguing.

Template classes

We can also create template classes so that they can operate on any type of data magically. The following example stores three member variables in the cthree class. The member function min returns the minimum value, and the member function Max returns the maximum value. We designed it as a template class so that this category can be applied to a wide range of data types:

#0001 template <class T>
#0002 class cthree
#0003 {
#0004 public:
#0005 cthree (T T1, t T2, t T3 );
#0006 T min ();
#0007 T max ();
#0008 PRIVATE:
#0009 t a, B, C;
#0010 };

The syntax is not so strange. Simply think of T as a familiar Int or float. The following is the definition of a member function:

#0001 template <class T>
#0002 t cthree <t>: min ()
#0003 {
#0004 t minab = A <B? A: B;
#0005 return minab <C? Minab: C;
#0006}
#0007
#0008 template <class T>
#0009 t cthree <t>: max ()
#0010 {
#0011 t maxab = A <B? B:;
#0012 return maxab <C? C: maxab;
#0013}
#0014
#0015 template <class T>
#0016 cthree <t >:: cthree (T T1, t T2, t T3 ):
#0017 A (T1), B (T2), C (T3)

#0018 {

0019 return;
#0020}

Pay more attention here. Template <class T> must be added before each member function, and the class name must be
Use cthree <t>.
The usage of template class is as follows:
#0001 # include <iostream. h>
#0002 void main ()
#0003 {
#0004 cthree <int> obj1 (2, 5, 4 );
#0005 cout <obj1.min () <Endl;
#0006 cout <obj1.max () <Endl;
#0007
#0008 cthree <float> obj2 (8.52,-6.75, 4.54 );
#0009 cout <obj2.min () <Endl;
#0010 cout <obj2.max () <Endl;
#0011
#0012 cthree <long> obj3 (646600l, 436647l, 363663l );
#0013 cout <obj3.min () <Endl;
#0014 cout <obj3.max () <Endl;
#0015}
The execution result is as follows:
2 5
-6.75
8.52
364873
646600
As I said earlier, T must be considered valid only when the template function supports all necessary operation operations for data type T. This restriction is true for template classes. To generate a cthree for certain classes, the class must provide the copy constructor and operator <because they are the T operation actions in min and Max member functions.

But if you are using another template classes, how do you know what operation actions are necessary? Well, this template classes should be described in the description file. If no, only the source code can reveal the secret. C ++ built-in data types such as int and float do not need to care about this requirement, because all built-in data types support all standard operation actions.

Templates compilation and Connection
For programmers, C ++ templates is very easy to design and use, but it is a big challenge for compilers and connectors. When the compiler encounters a template, it cannot generate a machine code for it immediately. It must wait until the template is specified with a certain type. From the programmer's point of view, this means that the full definition of the template function or template class will appear in every corner of the template. Otherwise, the compiler will not have enough information to help generate the target code. When multiple source files use the same template, the process becomes more complex. With different compilers, the technology for mastering this complexity is also different. There is a common technology called smart in Borland, which should be the easiest: The template code exists in the target file of every program code using the template, and the connector is responsible for copying and deleting. Suppose we have a program that contains two source files, A. cpp and B. cpp, and a three. H (which defines a template class named cthree ). Both a. cpp and B. cpp contain three. h. If a. cpp uses this template category as int and double, the compiler will generate an executable code for the template category of int and double in A. obj. If B. cpp uses this template category as int and float, the compiler will generate executable code for the template category of int and float versions in B. obj. Even though a. OBJ already has an int version, the compiler cannot understand it. Then, all duplicate parts will be deleted during the join process. See.

Template with Bubble Sorting

Template <class stype>
Void bubble (stype * item, int count)
{
Register int I, J;
Stype T;
For (I = 1; I <count; I ++)
{
For (j = count-1; j> = I; j --)
{
If (item [J-1]> item [J]) // if the current item is greater than the last one, two numbers are exchanged.
{
T = item [J-1];
Item [J-1] = item [J];
Item [J] = T;
}
}
}
}

Void main ()
{

Char STR [] = "htegshqqhsadqshdh ";
Int Len = strlen (STR );
Bubble (STR, Len );

Cout <STR <Endl;

Int num [] = {8, 4, 6, 3, 1, 2 };
Bubble (Num, 6 );
For (INT I = 0; I <6; I ++)
{
Cout <num [I] <Endl;
}
}

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.