1、函数模板注意事项
#include <iostream>
using namespace std;
template < typename T>
void mySwap ( T& a, T& b)
{
T temp = a;
a = b;
b = temp;
}
void test01 ( )
{
int a = 10 ;
int b = 20 ;
char c= 'c' ;
mySwap ( a, b) ;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
}
template < class T >
void func ( )
{
cout << "func 调用" << endl;
}
void test02 ( )
{
func< int > ( ) ;
}
int main ( )
{
test02 ( ) ;
system ( "pause" ) ;
return 0 ;
}
2、函数模板案例——数组排序
#include <iostream>
using namespace std;
template < class T >
void mySwap ( T& a, T& b)
{
T temp = a;
a = b;
b = temp;
}
template < class T >
void mySort ( T arr[ ] , int len)
{
for ( int i = 0 ; i < len; i++ )
{
int max = i;
for ( int j = i + 1 ; j < len; j++ )
{
if ( arr[ max] < arr[ j] )
{
max = j;
}
}
if ( max != i)
{
mySwap ( arr[ max] , arr[ i] ) ;
}
}
}
template < class T >
void printArray ( T arr[ ] , int len)
{
for ( int i = 0 ; i < len; i++ )
{
cout << arr[ i] << " " ;
}
cout << endl;
}
void test01 ( )
{
char charArr[ ] = "bacdef" ;
int num = sizeof ( charArr) / sizeof ( char ) ;
mySort ( charArr, num) ;
printArray ( charArr, num) ;
}
void test02 ( )
{
int intArr[ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ;
int num = sizeof ( intArr) / sizeof ( int ) ;
mySort ( intArr, num) ;
printArray ( intArr, num) ;
}
int main ( )
{
test02 ( ) ;
system ( "pause" ) ;
return 0 ;
}
3、普通函数与函数模板的区别
#include <iostream>
using namespace std;
int myAdd01 ( int a, int b)
{
return a + b;
}
template < class T >
T myAdd02 ( T a, T b)
{
reyurn a + b;
}
void test01 ( )
{
int a = 10 ;
int b = 10 ;
char c = 'c' ;
cout << myAdd01 ( a, c) << endl;
cout << myAdd02 ( a, b) << endl;
cout << myAdd02< int > ( a, c) << endl;
}
int main ( )
{
test01 ( ) ;
system ( "pause" ) ;
return 0 ;
}
4、普通函数和函数模板的调用规则
#include <iostream>
using namespace std;
void myPrint ( int a, int b)
{
cout << "调用普通函数" << endl;
}
template < class T >
void myPrint ( T a, T b)
{
cout << "调用模板" << endl;
}
void test01 ( )
{
int a = 10 ;
int b = 20 ;
char c1= 'a' ;
char c2= 'b' ;
myPrint ( c1, c2) ;
}
int main ( )
{
test01 ( ) ;
system ( "pause" ) ;
return 0 ;
}
5、模板的局限性
#include <iostream>
using namespace std;
class Person
{
public :
Person ( string name, int age)
{
this - > m_Name = name;
this - > m_Age = age;
}
string m_Name;
int m_Age;
} ;
template < class T >
bool myCompare ( T & a, T & b)
{
if ( a == b)
{
return true ;
}
else
{
return false ;
}
}
template < > bool myCompare ( Person & p1, Person & p2)
{
if ( p1. m_Name== p2. m_Name&& p1. m_Age== p2. m_Age)
{
return true ;
}
else
{
return false ;
}
}
void test01 ( )
{
int a = 10 ;
int b = 20 ;
bool ret = myCompare ( a, b) ;
if ( ret)
{
cout << "a==b" << endl;
}
else
{
cout << "a!=b" << endl;
}
}
void test02 ( )
{
Person p1 ( "Tom" , 20 ) ;
Person p2 ( "Tom" , 10 ) ;
bool ret = myCompare ( p1, p2) ;
if ( ret)
{
cout << "p1==p2" << endl;
}
else
{
cout << "p1!=p2" << endl;
}
}
int main ( )
{
test02 ( ) ;
system ( "pause" ) ;
return 0 ;
}