Fra*_*zzi 3 c++ templates class definition
我正在实现这个类:
#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
Run Code Online (Sandbox Code Playgroud)
我想ListNode在 中实现类ListNodeCode.h,但出现此错误:
[错误] 专门化成员 'List::ListNode::ListNode' 需要 'template<>' 语法
这是目前内部唯一的方法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
Run Code Online (Sandbox Code Playgroud)
我该如何正确实施呢?
注意ListNode是会员模板;并且有两个单独的模板参数,一个(即ListType)用于封闭模板List,一个(即NodeType)用于成员模板ListNode,因此定义应该是:
template <typename ListType> // for the enclosing class template
template <typename NodeType> // for the member template
List<ListType>::ListNode<NodeType>::ListNode(const NodeType& value,const ListNode<NodeType>*const pElement, const ListNode<NodeType>*const nElement) {
// ...
}
Run Code Online (Sandbox Code Playgroud)