今天将primer里面的Queue实现了下,自我感觉c++模版的使用应该注意以下几点:
1. 模版的编译类型,编译器一般都支持包含编译类型,这种形式和以往不同的是在头文件中包含实现文件。
2. 模版的实例化时间,只编译模版文件的时候对于有些类型不匹配可能检查不出来,直到使用时才会实例化,定义类并不实例化成员函数,使用时才实例化,实例化时由对象决定类型,而非参数推断。
3. 模版的友元的声明,一般应该限制同类型的友元。
#ifndef _QUEUE_H_
#define _QUEUE_H_
//#include"QueueItem.h"
template<class Type> class Queue;
template <class T> class QueueItem
{
friend class Queue<T>;
public:
QueueItem():item(0), next(0){};
QueueItem(T t):item(t),next(0){};
private:
T item;
QueueItem * next;
};
template<class Type> class Queue
{
public:
Queue():head(0),tail(0){}
template<class It> Queue(It beg, It end):head(0),tail(0){Copy_Elems(beg, end);}
Queue& operator=(const Queue&);
~Queue();
void Push(Type t);
Type Front() const;
bool Empty()const;
Type Pop();
private:
//void Copy_Elems(Queue &q);
template<class It>void Copy_Elems(It beg ,It end);
QueueItem<Type> *head;
QueueItem<Type> *tail;
};
#include "Queue.cpp"
#endif
//#include "Queue.h"
template <class Type> void Queue<Type>::Push( Type t)
{
QueueItem<Type> *qi = new QueueItem<Type>(t);
if( Empty() )
{
head = qi;
tail = qi;
}
else
{
tail->next = qi;
tail = qi;
}
}
template<class Type>
bool Queue<Type>::Empty()const
{
return (head==0);
}
template<class Type>
Type Queue<Type>::Front()const
{
if( !Empty())
return head->item;
else
return 0;
}
template <class Type>
Queue<Type> &Queue<Type>::operator=(const Queue<Type>&q)
{
QueueItem<Type> *qi = q.head;
while(qi)
{
Push(qi);
qi=qi->next;
}
}
template<class Type>
Queue<Type>::~Queue()
{
while(!Empty())
Pop();
}
template<class Type>
Type Queue<Type>::Pop()
{
QueueItem<Type>*p = head;
head = head->next;
Type temp = p->item;
delete p;
return temp;
}
template<class Type> template <class It>
void Queue<Type>::Copy_Elems(It beg, It end)
{
while(beg != end)
{
Push(*beg);
beg++;
}
}