瞭解C++模板的某些方面有助於java泛型的基礎,認清邊界問題。
模板是C++支持參數化程序設計的工具,通過它可以實現參數化多態性。所謂的參數化多態性,就是程序所處理的對象的類型參數化,
使得一段程序可以用於處理多種不同類型的對象
int abs(int x){
return x<0? -x:x; }
double abs(double x) {
return x<0? -x:x; }
參數不同,功能一樣,爲了提高效率,基於函數調用時提供的參數類型
函數模板定義形式:
template <class T>
template<typename T>
類型命 函數命(參數表){ 函數體的定義; }
函數模板,編譯器從實參的類型推導出函數的參數類型
template <typename T>
T abs( T x )
{ return x < 0 ? -x : x; }
模板DEMO:
#include "stdafx.h"
#include"iostream"
using namespace std;
using namespace System;
template <class T>
void outputArray(const T * P_array, const int count){
for (int i = 0; i < count; i++)
cout << P_array[i] << " ";
cout << endl;
}
int main(array<System::String ^> ^args)
{
const int aCount = 8 , bCount=8 , cCount=20;
int aArray[aCount] = { 1, 2, 3, 4, 5, 6, 7, 8 };
double bArray[bCount] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8 };
char cArray[cCount] = "Welcome to see you!";
cout << "----------------------------" << endl;
outputArray(aArray, aCount);
cout << "----------------------------" << endl;
outputArray(bArray, bCount);
cout << "----------------------------" << endl;
outputArray(cArray, cCount);
system("pause");
return 0;
}
類模板:
template <模板參數表>
class 類名{ 類成員聲明}
在類模板意外定義其他成員函數
類型名 類名<T> ::函數名(參數表)
DEMO:
#include "stdafx.h"
#include"iostream"
#include"cstdlib"
using namespace std;
using namespace System;
struct Student
{
int id;
float gpa;
};
//--------------------------------------------------------
template <class T>
class Store
{
private:
T item;
int haveValue;
public:
Store(void);
T GetElem(void);
void PutElem(T x);
};
//--------------------------------------------------------
template <class T>
Store<T> ::Store(void) :haveValue(0){
}
//--------------------------------------------------------
template <class T>
T Store<T>::GetElem(void){
if (haveValue == 0){
cout << "No item present! " << endl;
exit(1);
}
return item;
}
//---------------------------------------------------------
template <class T>
void Store<T> ::PutElem(T x){
haveValue++;
item = x;
}
//-------------------------------------------------------
int main(array<System::String ^> ^args)
{
Student g = { 1000, 23 };
Store<int> S1, S2;
Store<Student> S3;
Store<double> D;
S1.PutElem(3);
S2.PutElem(-7);
cout << S1.GetElem() <<" "<< S2.GetElem() << endl;
S3.PutElem(g);
cout << "The student id is" << S3.GetElem().id << endl;
cout << "Retrieving object D ";
cout << D.GetElem() << endl;
system("pause");
return 0;
}