c++ - 在 C++ 中创建新的模板容器类型

标签 c++ templates stl containers

好的,所以我正在尝试在 C++ 中实现一个模板化的循环双向链表。我遇到的问题是,当我尝试将类定义和函数分别分离到 .h 和 .cpp 文件中时,编译器不断向我吐出关于没有模板参数的错误。

这里是头文件,cdl_list.h

#ifndef CDL_LIST_H
#define CDL_LIST_H

#include <iostream>


using namespace std;


template <typename T>
class cdl_list {

        public:

        cdl_list(){
                first = last = current = NULL;};     // constructor, "current" = "null"
        ~cdl_list();    // deconstructor
        void insertFromFront (T &);     // inserts an element of type T in the front properly
        void insertFromBack (T &);      // inserts an element of type T in the back properly
        void deleteFront();     // removes the first element in the list, updating relevant pointers
        void deleteBack();      // removes the last element in the list, updating relevant pointers
        void reset();   // makes the "current" pointer the front element
        void next();    // makes the "current" pointer the next node neighbor
        T currentValue();       // return the data in the node that "current" refers to
        void deleteCurrent(); // delete the node that the current pointer refers to; current = old -> next
        bool isEmpty(); // returns true if and only if the list is empty
        void print();   // displays the current data in the linked list


        private:

        struct listNode* first;
        struct listNode* last;
        struct listNode* current;


        protected:

        struct listNode {
                listNode* prev; // "previous" pointer
                T data; // data in the node
                listNode* next; // "next" pointer
        };
};

#include "cdl_list.h"
#include <iostream>

using namespace std;



//And here is the .cpp file, what I have so far, because I can't even get just this one function to compile

template < typename T > void cdl_list::insertFromFront(const T &frontInsert) {
        listNode *oldFirst;
        oldFirst = (listNode *) malloc(sizeof(listNode));
        oldFirst = first;
        oldFirst -> prev = frontInsert;
        while(current -> next != first)
                current = current -> next;
        frontInsert -> prev = current;
        current -> next = frontInsert;
        first = frontInsert;

}



#endif

最佳答案

不幸的是,由于 C++ 编译过程的工作方式,它们需要在同一个文件中(除此之外还有其他解决方法,但这是最常见的一种)。参见 http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12了解更多详情。

关于c++ - 在 C++ 中创建新的模板容器类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5189153/

相关文章:

c# - 从 C++ 到 C# 的二进制/十六进制数据的编码/DllImport

c++ - 可变函数模板中的歧义

c++ - 为什么具有显式声明的 move 构造函数的类会失败 `std::is_move_constructible_v` ?

c++ - 如何使用 set<pair<int,int>>::iterator 迭代 set<pair<int,int>>st 中的值?

c++ - .*& 运算符是做什么的?

c++ - C stdio 字符编码

c++ - 委托(delegate)执行者是否受参数评估顺序的影响?

c++ - 在 Visual Studio 2013 中使用 Libusb

c++ - 在cpp中定义模板特化?

c++ - 何时在 C++ 对中使用点和箭头运算符?