c++ - 使用模板参数传递链表的节点类型和数据类型

标签 c++ templates

在我的链表类中,我想传递数据的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/

相关文章:

以非专用模板作为值的 C++ hash_map

c++ - std::move 作为参数的参数类型

c++ - 如何检测析构函数期间异常是否处于事件状态?

c++ - 为什么 std::bitset 只取 constexpr 值?

c++ - 动态类成员

python - Jinja2 模板 - for 循环

c++ - 调用基类变量时出现段错误

c++ - 应用程序无法正确启动 0xc0000142 CreateProcessWithLogonW

c++ - 将运算符 = 传递给函数对象

C++ 类对非类型模板参数的部分特化