在我的链表类中,我想传递数据的dataType以及包含数据的节点类型作为模板参数存储,但是我一直遇到编译错误。
继承节点类
llist.h
template<class itemType>
class Node {
itemType item{};
Node* next{};
Node* prev{};
public:
Node* getnext() { return next; }
Node* getprev() { return prev; }
itemType getitem() { return item; }
};
这是链表类。llist.h
template <class itemType, class nodeType>
class LinkedList
{
//I am trying to say
//using node=Node<itemType>
//but dont want to use Node directly and want to get the type of Node from template argument
using node = nodeType<itemType>; node* head{};
public:
node* getHead() { return head; }
};
当我尝试从main()实例化它时,出现编译器错误int main()
{
std::cout << "Hello World!\n";
LinkedList<int, Node<int> > list;
list.getHead();
}
错误如下:1>X:\code1\Blib\Blib\llist.h(16,23): error C2143: syntax error: missing ';' before '<'
1>C:\code\Blib\Blib\llist.h(21): message : see reference to class template instantiation 'LinkedList<itemType,nodeType>' being compiled
1>C:\code\Blib\Blib\llist.h(16,1): error C2059: syntax error: '<'
1>C:\code\Blib\Blib\llist.h(16,1): error C2238: unexpected token(s) preceding ';'
1>Done building project "Blib.vcxproj" -- FAILED.
最佳答案
如果要将nodeType
用作nodeType<itemType>
之类的模板,则可以将其声明为template template parameter。
template <class itemType, template <typename> class nodeType>
class LinkedList
然后像LinkedList<int, Node> list;
LIVE如果要像现在一样将其声明为type template parameter,则只需将其用作
template <class itemType, class nodeType>
class LinkedList
{
using node = nodeType;
...
};
LIVE
关于c++ - 使用模板参数传递链表的节点类型和数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63664916/