函式樣板
函数模板的声明形式如下:
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
template < 樣板參數型態 樣板參數名 , …其他樣板參數 >
原型回傳型態 函式名稱(參數型態 原型參數名, ...)
{
程式碼;
}
函式樣板:參數型態可用關鍵字 class
或 typename
表示泛用型態 (即任何型態);或是一個已宣告的資料型態,如int 與自定類。
原型中的參數型態若是已宣告的資料型態,則是一種特殊化的函式樣板。
#include <iostream>
using namespace std;
int Add(int a, int b)
{
return a + b;
}
template <class T>
T Add(T a, T b)
{
return a + b;
}
int main()
{
int c1;
double c2;
c1 = Add(10, 20);
c2 = Add(10.3, 20.4);
return 0;
}
C++函式樣板寫一個泡沫排序法(BubbleSort):
#include <iostream>
#include <string>
using namespace std;
template <class T>
void BubbleSort(int n, T A[])
{
T temp;
int i, j;
for (i = n - 1; i>1; i--) //for(i=0; i<n-1; i++)
{
for (j = 0; j<i; j++) //for(j=0; j<n-1; j++)
{
if (A[j] > A[j + 1])
{
temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
}
}
}
}
template <class T>
void PrintArray(int n, T A[])
{
int i;
for (i = 0; i<n; i++)
cout << A[i] << " ";
cout << endl;
}
int main()
{
int n = 5;
int A1[5] = { 12,33,2,4,22 };
double A2[5] = { 12.43, 12.33, 2.4 ,4.66 ,22.1 };
char A3[5] = { 'G','B',