C + + Template learning

Source: Internet
Author: User
Tags class definition float max

1. the concept of templates.

We have learned overload (overloading), for overloaded functions, the check mechanism of C + + can be different from the function parameter and the owning class. Call the overloaded function correctly. For example, to find the maximum value of two numbers, we define the max () function to define different overloaded (overload) versions of different data types separately.

Function 1.

int max (int x,int y);
{return (x>y)? X:y;}

Function 2.
Float max (float x,float y) {
Return (x>y)? X:y;}

Function 3.
Double Max (double x,double y)
{return (c>y)? X:y;}

But if in the main function, we define a char, a, a, respectively; Then, when you execute Max (A, b), the program will go wrong because we do not have an overloaded version of the char type defined.

Now, we re-examine the max () function above, they all have the same function, that is, to find the maximum value of two, can write a set of code to solve the problem? This avoids the invocation error caused by the overloaded function definition. In order to solve the above problems, C + + introduces template mechanism, template definition: template is a tool to implement code reuse mechanism, it can implement type parameterization, that is, the type is defined as a parameter, thus realizing the real code reusability. Template can be divided into two categories, one is a function template, the other is a class template.

2. How function templates are spelled

The general form of a function template is as follows:

Template <class or you can use typename t>

return type function name (formal parameter list)
{//function definition Body}

Description: Template is a keyword that declares templates, which declares that a template keyword class cannot be omitted, and if the type parameter is extra, the class < type parameter list > can contain the base data type can contain the class type, before each parameter.

Please see the following procedure:

Test.cpp

#include <iostream>

Using Std::cout;

Using Std::endl;

Declare a function template to compare the size of the parameters of the input two of the same data type, class can be replaced by TypeName,

T can be replaced by any letter or number.

Template <class t>

T min (t x,t y)

{return (x<y)? X:y;}

void Main ()

{

int n1=2,n2=10;

Double d1=1.5,d2=5.6;

cout<< "Small Integer:" <<min (N1,N2) <<endl;

cout<< "Smaller real numbers:" <<min (D1,D2) <<endl;

System ("PAUSE");

}

 

Program Analysis: the main () function defines two integer variable n1, n2 two double type variable d1, d2 then calls Min (N1, N2); That is, the instantiation function template T min (t x, t y) where T is of type int, the minimum value in the N1,N2 is calculated. When you call min (d1,d2), the minimum value in the D1,D2 is calculated.

3. how class templates are written

Define a class Template:

Template < class or you can also use typename T >
Class Name {
Class definition ...
};

Description: Where the template is a keyword that declares templates, it declares a template, the template parameter can be one, or it can be multiple.

For example, define a class template:

ClassTemplate.h
#ifndef CLASSTEMPLATE_HH

#define CLASSTEMPLATE_HH

Template<typename T1,typename t2>

Class myclass{

Private

T1 I;

T2 J;

Public

MyClass (T1 A, T2 b);//constructor

void Show ();

};

This is a constructor

Note these formats

Template <typename T1,typename t2>

Myclass<t1,t2>::myclass (T1 a,t2 B): I (a), J (b) {}

This is void show ();

Template <typename T1,typename t2>

void Myclass<t1,t2>::show ()

{

cout<< "i=" <<I<< ", j=" <<J<<endl;

}

#endif

Test.cpp

#include <iostream>

#include "ClassTemplate.h"

Using Std::cout;

Using Std::endl;

void Main ()

{

myclass<int,int> Class1 (3,5);

Class1.show ();

Myclass<int,char> Class2 (3, ' a ');

Class2.show ();

Myclass<double,int> CLASS3 (2.9,10);

Class3.show ();

System ("PAUSE");

}

The final results show:

4. Non-type template parameters

In general, a non-type template parameter can be a constant integer (including an enumeration) or a pointer to an externally linked object.

That is, floating-point numbers do not work, and pointers to internal linked objects are not possible.


Template<typename T, int maxsize>

Class stack{

Private:

T Elems[maxsize];

...

};

Int Main ()

{

Stack<int, 20> Int20stack;

Stack<int, 40> Int40stack;

...

};

5. Using the template type

Sometimes the template type is a container or a class, to use the type under that type can be called directly, the following is a printable STL in the order and chain of the container template function

Template <typename t>
void print (T v)
{
T::iterator Itor;
for (Itor = V.begin (); Itor! = V.end (); ++itor)
{
cout << *itor << "";
}
cout << Endl;
}

void Main (int argc, char **argv) {
List<int> l;
L.push_back (1);
L.push_front (2);
if (!l.empty ())
Print (l);
Vector<int> VEC;
Vec.push_back (1);
Vec.push_back (6);
if (!vec.empty ())
Print (VEC);
}

Print results

Implicit type conversions for type deduction
Before deciding on the template parameter type, the compiler performs the following implicit type conversions:

Left-value transformation
Modifier Word Conversion
Conversions from a derived class to a base class

See "C + + Primer" ([note 2],p500) for a complete discussion of this topic.

In short, the compiler weakens certain types of properties, such as the Lvalue property of the reference type in our example. For example, a compiler uses a value type to instantiate a function template instead of using the appropriate reference type.

Similarly, it instantiates a function template with a pointer type, rather than the corresponding array type.

It removes the const modifier, never instantiates a function template with a const type, always uses the corresponding non-const type, but for pointers, pointers and const pointers are different types.

The bottom line is that automatic template argument deduction contains type conversions, and some type properties are lost when the compiler automatically determines template parameters. These type properties can be persisted when using explicit function template parameter declarations.

6. Template-Specific
If we are going to write a function for a particular type of template function (class), we need to use the template's specificity, such as when we are going to call Max with a long type, and return a small value (forgive me for the inappropriate example):
Template<>//This represents the following is a template function
Long max<long> (long A, long B)//For VC, <long> here can be omitted
{
Return a > B? b:a;
}
In fact, the so-called special, is to replace the compiler to complete the specific type of work, the modern template Library, a large number of use of this technique.
For partial specificity, only some of the types in the template type are specific, such as

TEMPLATE<T1, t2>

Class MyClass;

TEMPLATE<T1, t2>

Class Mycalss<int, t2>//partial localization
7. Imitation functions
The term functor often appears in template libraries (such as STL), so what is an imitation function?
As the name implies: the functor is able to work like a function of things, please forgive me to use something such a pronoun, I will slowly explain below.
void Dosome (int i)
This dosome is a function that we can use in this way: Dosome (5);
So, is there anything that can work like this?
Answer 1: The object with the () operator is overloaded, so there is a need to clarify two points:
1 An imitation function is not a function, it is a class;
2 The functor overloads the () operator so that it's pair you can call it like a function (the code is in the form of a call like:
struct Dosome
{
void operator () (int i);
}
Dosome Dosome;
Here the class (for C + +, the struct and the class are the same) overloads the () operator, so its instance dosome can be used Dosome (5); It's exactly the same as the function call above, isn't it? So dosome is an imitation function.

There's actually an answer. 2:
The object to which the function pointer is pointing.
typedef void (*DOSOMEPTR) (int);
typedef void (Dosome) (int);
Dosomeptr *ptr=&func;
dosome& dosome=*ptr;

Dosome (5); This is exactly the same as the function call.
Of course, the member function pointed to by the Answer 3 member function pointer is the expected answer.

8. Use of the functor function
Both object and function pointers can be passed as arguments or stored as variables. So we can pass an imitation function to a function that calls the functor as needed (a bit like a callback).
In the STL Template Library, this technique is used extensively to realize the "flexibility" of the library.
Like what:
For_each, its source code is roughly as follows:
template< TypeName Iterator, TypeName Functor >
void For_each (Iterator begin, Iterator end, Fucntor func)
{
for (; begin!=end; begin++)
Func (*begin);
}

This for loop iterates through each element in the container, invokes the functor Func for each element, and implements the idea of programming "do the same thing for every element".

In particular, if an affine function is an object, this object can have member variables, which allows the functor to have "state", thus achieving greater flexibility.

C + + Template learning

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.