stl - C++ Template:error: 'Node' is not a template type
巴扎黑
巴扎黑 2017-04-17 13:02:02
0
2
847
template <class T>
struct Node{
    T val;
    Node *next;
    Node(T &t){
        this->val = t;
        this->next = NULL;
    }
};

template <class T>
class SingleList {
public:
    SingleList();
    ~SingleList();
    void push_front(T &t);

private:
    int m_nListCount;
    Node<T> *m_head;
};

template <class T>
SingleList<T>::SingleList(){
    m_head = NULL;
    m_nListCount = 0;
}

template <class T>
SingleList<T>::~SingleList(){
    Node<T> *p, *pNext;
    for (p = m_head; p != NULL ; p = pNext) {
        pNext = p->next;
        free(p);
    }
    m_nListCount = 0;
}

template <class T>
void SingleList<T>::push_front(T &t){
    Node<T> *pNode = (Node<T> *)malloc(sizeof(Node<T>));
    if(NULL != pNode){
        pNode->val = t;
        pNode->next = m_head;
        m_head = pNode;
        m_nListCount++;
    }
}

代码全部放在头文件中,但是使用Clion编译提示:error: 'Node' is not a template type,求解答!

巴扎黑
巴扎黑

reply all(2)
洪涛

I tried it with vs2015 and it can be compiled and passed.
But when compiling with g++Node<T> *pNode = (Node<T> *)malloc(sizeof(Node<T>));
An error occurs when reading this sentence: there are no arguments to 'malloc' that depend on a template parameter, so a declaration of 'malloc' must be available [-fpermissive]

changed to

Node<T> *pNode = new Node<T>(); 

It can be compiled (it is recommended that classes and templates use new to allocate memory, because new can automatically call the default constructor, and also has built-in sizeof, type conversion and type safety check functions)

But I can’t try it because of Clion. . It should be a compiler implementation problem. .

Ty80

template <class T>
struct Node{

T val;
Node<T> *next;
Node(T &t){
    this->val = t;
    this->next = NULL;
}

};

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template