1. 属于genetic programming
2. 到compile的时候instantiate相关的类。
3. 分为class template和function template。
4. 用法:
在声明class前加上template <class XXX>
到时候implement的时候,所有的int/float/double 等都变成XXX用就好了。
例子:linked list 和 stack 同时用template
5. 值得注意的是,不能在头文件声明template然后在.cpp实现,原因很简单,因为如果这样其他的.cpp file在compile的时候就不知道instantiate哪一个了。(Reference:http://stackoverflow.com/questions/1724036/splitting-templated-c-classes-into-hpp-cpp-files-is-it-possible)
#include <iostream>
using namespace std;
template< class T>
class LinkedElement
{
public:
LinkedElement(T value):next (NULL), data(value)
{
}
~LinkedElement()
{
}
LinkedElement * getNext()
{
return next;
}
T getValue()
{
return data;
}
void setNext(LinkedElement * ele)
{
next = ele;
return;
}
void setValue(T value)
{
data = value;
return;
}
private:
LinkedElement * next;
T data;
};
template< class T>
class Stack
{
public:
Stack(int N):top(NULL),size(N){}
~Stack(){}
bool push(T value)
{ //NOTICE:linked list的指针是这样定义的
LinkedElement<T>* Node = new LinkedElement<T>(value);
if (Node == NULL)
return false;
else
{
Node->setNext(top);
top = Node;
return true;
}
}
T pop(){
if (!isEmpty())
{
T value = top->getValue();
top = top->getNext();
return value;
}
return -1;
}
bool isFull(){
return false;
}
bool isEmpty(){
if (top!=NULL)
return false;
else
return true;
}
private:
int size;
LinkedElement<T> * top;
};//NOTICE:另外,如果想类外implement成员函数的话
/*要么这样
template <class T>
void Stack<T>::pop()
{
}*/
/*要么这样
void Stack<class T>::pop()
{
}*/
int main()
{ //template指针,和int * 没有啥区别
//Stack<float> * S = new Stack<float>(5);
Stack<int> * S = new Stack<int>(5);
S->push(5.2);
S->push(4);
//cout<<S->top->getValue()<<endl;
system("PAUSE");
return 0;
}