I. Basics
In the new C ++ standard, typename is recommended for the following template type keyword class.
1.1 General Functions
Template <class tType> re-type func-Name (parameter list)
{
// Body of funtion
}
For example:
Template <Class X> void swap (X & A, X & B)
{
X temp;
Temp =;
A = B;
B = temp;
}
# Include <iostream>
Using namespace STD;
Int main ()
{
Int I = 10, j = 20;
Swap (I, j );
Cout <"swapped I, j:" <I <j <'\ n ';
}
1.2 generic
Template <class tType> class-name
{
// Body of class
}
For example:
# Include <iostream>
Using namespace STD;
Const int size = 10;
Template <class stacktype> class Stack
{
Stacktype stack [size];
Int TOS; // stack top Index
Public:
Stack () {TOS = 0 ;}
Void push (stacktype ob)
{
If (TOS = size)
{
Cout <"Stack is full. \ n ";
Return;
}
Stack [TOS] = ob;
ToS ++;
}
Stacktype POP ()
{
If (TOS = 0)
{
Cout <"Stack is empty. \ n ");
Return 0;
}
ToS --;
Return stack [TOS];
}
}
Int main ()
{
Stack <char> S1;
S1.push ('A ');
S1.push ('B ');
While (s1.tos)
{
Cout <"Pop S1:" <s1.pop () <'\ n ';
}
}
In essence, I think templates implement the definition of general logic and enableAlgorithmIndependent from the data type (due to the actualProgramThe data type must be given first, so the compiler needs to parse the template first, similar to the macro command ). the above stack classes may actually include integer stacks or floating-point stacks. if you do not use a template, You need to compile a stack class for each type. In fact, the operations are exactly the same. by the way, STL is a group of templates carefully designed by experts.
Ii. Improvement
2.1 multi-type templates
There can be multiple template types, such:
Template <typename orgtype, typename destype> destype Covent (orgtype org)
{
Return (destype) org;
}
2.2 heavy load
Similarly, templates can also be reloaded. For example, you can define a function with the same name as a reload function template or define another template with the same name but different types of definitions.
Template <> void swap <int> (Int & A, Int & B)
{
Int temp;
Temp =;
A = B;
B = temp;
}
2.3 default type
Template <Class X = int> class myclass
{
// Body of class
}
2.4 use non-type parameters
Template <class stype, int size> class Stack
{
Stype stackbuffer [size];
......
}
Call time:
Stack <int, 20> intstack;
2.5typenaem and export keywords
Typename notifies the compiler that the template declaration uses a type name instead of an object name. The previous template type keyword class can be replaced with it.
Before using the template declaration, export allows other files to use the template defined in other files by specifying the template declaration instead of all copies.