我實施這個類:C++ - 實施內部模板類的模板方法在一個單獨的文件
#ifndef LIST_H
#define LIST_H
template <typename ListType> class List{
public:
enum ListPosition{LIST_START=-2,LIST_END=-1};
enum Order{ASCENDANT,DESCENDANT};
template <typename NodeType> class ListNode{
public:
ListNode(const NodeType &value,const ListNode<NodeType>*const pElement, const ListNode<NodeType>*const nElement);
~ListNode();
ListNode<NodeType> *const previous() const;
ListNode<NodeType> *const next() const;
void setPrevious(const ListNode<NodeType> *const pElement);
void setNext(const ListNode<NodeType> *const nElement);
void setValue(const NodeType& value);
private:
ListNode<NodeType> *pElement;
ListNode<NodeType> *nElement;
NodeType *value;
};
List();
List(const List<ListType> &list);
~List();
bool contains(const ListType& value) const;
ListType& get(const int pos) const;
ListNode<ListType>& getNode(const int pos) const;
void add(const ListType& value);
void add(const int pos, const ListType& value);
void addAll(const int pos, const List<ListType>& list);
void set(const int pos, const ListType& value);
void remove(const int pos);
void remove(const ListType& value);
void order(Order order);
int size() const;
bool operator==(const List<ListType>& list) const;
void operator=(const List<ListType>& list);
operator const char *() const;
ListType& operator[](const int pos) const;
const ListNode<ListType>& operator[](const ListType& value) const;
protected:
ListNode<ListType> *firstNode;
ListNode<ListType> *lastNode;
int _size;
};
#include "ListCode.h"
#include "ListNodeCode.h"
#endif
我想實現ListNodeCode.h
ListNode
類,但我得到這個錯誤:
[Error] specializing member 'List::ListNode::ListNode' requires 'template<>' syntax
而且這是唯一的方法,此刻,裏面ListNodeCode.h
:
#ifndef LISTNODECODE_H
#define LISTNODECODE_H
template <typename NodeType> List<NodeType>::ListNode<NodeType>::ListNode(const NodeType& value,const ListNode<NodeType>*const pElement, const ListNode<NodeType>*const nElement){
this->value=new NodeType();
*(this->value)=value;
this->pElement=pElement;
this->nElement=nElement;
cout << "Node created, (Value: " << (*this->value) << ", previous: " << pElement << ", next: " << nElement;
}
#endif
我該如何正確實施它?
謝謝,它的工作!但是有沒有辦法讓這兩個類都有相同的模板參數?如果是的話,這將是有用的,因爲我不必使用「NodeType」模板參數 –
@FrancescoRizzi你的意思是'ListNode'將總是使用'List'的相同模板參數?那爲什麼不讓它成爲非模板類呢? – songyuanyao
「價值」和其他屬性是否屬於正確類型? (ListType代替NodeType) –