模板函数
# include <iostream>
# include <cstdlib>
using namespace std;
template < class T >
T func ( T n)
{
T result;
result = n * n + 5 ;
}
int main ( )
{
func ( 5 ) ;
cout << "func(5)=" << func ( 5 ) << endl;
cout << "func(5.5)=" << func ( 5.5 ) << endl;
}
非类型参数的函数模板
# include <iostream>
# include <cstdlib>
using namespace std;
template < class arrayType , int array_size>
void showArray ( arrayType ( & array) [ array_size] )
{
int i;
for ( i= 0 ; i< array_size; i++ ) {
cout << i << " " << array[ i] << endl;
}
}
int main ( )
{
int a[ ] = { 1 , 2 , 3 , 4 , 5 } ;
showArray ( a) ;
float b[ ] = { 2.5 , 25.2 , 44.5 , 66.2 } ;
showArray ( b) ;
}
类模板
# include <iostream>
# include <cstdlib>
using namespace std;
template < class type >
class function
{
private :
type y;
public :
function ( type x) {
y= x;
}
void show ( ) {
cout << "y=" << y << endl;
}
} ;
int main ( )
{
function< int > fun1 ( 1 ) ;
fun1. show ( ) ;
function< float > fun2 ( 2.99 ) ;
fun2. show ( ) ;
function< char > fun3 ( 'a' ) ;
fun3. show ( ) ;
}
堆栈类模板
# include <iostream>
# include <cstdlib>
using namespace std;
template < class Type = int , int size = 5 >
class Stack
{
private :
Type st[ size] ;
int top;
public :
Stack ( ) {
top = - 1 ;
}
void push ( Type data) ;
Type pop ( ) ;
int getNum ( ) {
return top+ 1 ;
}
} ;
template < class Type , int size>
void Stack < Type, size> :: push ( Type data)
{
if ( ( top+ 1 ) > ( size- 1 ) ) {
cout << "man!" << endl;
}
else {
st[ ++ top] = data;
}
}
template < class Type , int size>
Type Stack < Type, size> :: pop ( )
{
return st[ top-- ] ;
}
int main ( )
{
Stack < > stk1;
stk1. push ( 1 ) ;
stk1. push ( 2 ) ;
stk1. push ( 3 ) ;
while ( stk1. getNum ( ) )
{
cout << "stk1:" << stk1. pop ( ) << endl;
}
cout << "stk1 num:" << stk1. getNum ( ) << endl;
Stack < float > stk2;
stk2. push ( 1.2 ) ;
stk2. push ( 2 ) ;
stk2. push ( 3.6 ) ;
while ( stk2. getNum ( ) )
{
cout << "stk2:" << stk2. pop ( ) << endl;
}
cout << "stk2 num:" << stk2. getNum ( ) << endl;
Stack < char * , 2 > stk3;
stk3. push ( "aaa" ) ;
stk3. push ( "bbb" ) ;
stk3. push ( "ccc" ) ;
while ( stk3. getNum ( ) )
{
cout << "stk3:" << stk3. pop ( ) << endl;
}
cout << "stk3 num:" << stk3. getNum ( ) << endl;
}