模板參數格式爲 template<typename T>class Thing .
我們使用模板,就是爲了泛型編程,如使用類型參數 typename T,就能實現相同算法下不同類型參數的統一編程。
而模板參數爲 類模板 ,也是泛型編程的目的。試想一下,在一個類中,可調用一個系列的類,是不是很酷?只要這一個系列的類都有着我們需要的特徵,那麼我們就能通過使用一個模板類來使用它們,重用代碼!
模板參數的格式爲template<typename T>class Thing. 其中, template<typename T>class 爲類型, Thing爲參數。
我被這句話搞混了好一會兒。MB,直接跟我說怎麼理解它不就得了。我們逆向去理解它。記住它是一個模板類,它的格式應爲
<typename T>
class Thing{...};
對比上面的格式,推測出 只要某個 模板類 的模板參數爲<typename T>,那麼這個模板類就可以作爲 該 模板 的參數。
C++除了STL思想外,其它都是狗屁。(C程序員)
既然那麼有用,咱這些coder也來學習一下吧。貼上代碼,大家好好理解一下。
/* stacktp.h */
#ifndef STACKTP_H_
#define STACKTP_H_
template <class Type>
class Stack
{
private:
enum {MAX = 10};
Type items[MAX];
int top;
public:
Stack();
bool isempty();
bool isfull();
bool push(const Type & item);
bool pop(Type & item);
};
template <class Type>
Stack<Type>::Stack()
{
top = 0;
}
template <class Type>
bool Stack<Type>::isempty()
{
return top == 0;
}
template <class Type>
bool Stack<Type>::isfull()
{
return top == MAX;
}
template <class Type>
bool Stack<Type>::push(const Type &item)
{
if(top < MAX)
{
items[top++] = item;
return true;
}
else
return false;
}
template <class Type>
bool Stack<Type>::pop(Type & item)
{
if(top > 0)
{
item = items[--top];
return true;
}
else
return false;
}
#endif
/* main.cpp */
#include<iostream>
#include"stacktp.h"
using namespace std;
template <template <typename T> class Thing>
class Crab
{
private:
Thing<int> s1;
Thing<double> s2;
public:
Crab(){};
bool push(int a, double x){return s1.push(a) && s2.push(x);}
bool pop(int &a,double &x){return s1.pop(a) && s2.pop(x);}
};
int main()
{
Crab<Stack> nebula;
int ni;
double nb;
cout<<"Enter int double pairs,such as 4 3.5(0 0 to be end):\n";
while(cin >> ni >> nb && ni>0 && nb > 0)
{
if(!nebula.push(ni,nb))
break;
}
while(nebula.pop(ni,nb))
cout<< ni <<", "<< nb <<endl;
cout<< "Done.\n";
return 0;
}
我沒做註釋,不好意思了啊。