简体   繁体   中英

Typedef pointer in a Class Template

I've made a basic linked list, the list had originally held integers, I'm trying to change the list to a template class.

My node class is called TLLNode ,

TLLNODE.h

#pragma once
template<class T>
class TLLNode{
    friend class TLL;
public:
    TLLNode(T data);typedef TLLNode<T>* TLLPtr;
private:
    TLLNode<T> data;
    TLLNode *next;

};

template<class T>
TLLNode<T>::TLLNode(T dataIn) : data(dataIn){

}

template<class T>
using  TLLNode<T>* TLLPtr;

and my list class to initialize and implement my functions is called TLL

TLL.h

#pragma once
#include <iostream>
#include"TLLNode.h"
using std::cout;
using std::endl;

template<class T>
class TLL{
public:
    TLL();
    TLL(const TLL&);
    void insert(T);
    void display();
    ~TLL();
private:
    TLLPtr head;
    TLLPtr newNode;
    TLLPtr curr;
    int size;
};

template<class T>
TLL<T>::TLL() : head(NULL), size(0){

}
// Not implemented yet
template<class T>
TLL<T>::TLL(const TLL& obj){

}
template<class T>
void TLL<T>::insert(T data){
    if (head == NULL)
        head = new TLLNode(data);
    else{
        newNode = new TLLNode(data);
        newNode->next = head;
        head = newNode;
    }
}
template<class T>
void TLL<T>::display(){
    curr = head;
    while (curr != NULL){
        cout << curr->data << endl;
        curr = curr->next;
    }
}
template<class T>
TLL<T>::~TLL(){
    while (head != NULL){
        curr = head;
        head = head->next;
        delete curr;
    }
}

I had been using typedef TLLNode* TLLPtr; when the list was of type int, but typedef for templates seems to be illegal.

I've tried a few different ways to get this to work and can't get any solution to work, I came across this post using , I've tried to use this solution without success, the code seems identical to what I want to do, bar the use of pointers.

I haven't tried the older solution in that post yet, using a struct. Are either solutions going to work for me and if not is there an alternative?

I realize there's probably mistakes in my code other than the issue I'm discussing, I'd like to try to figure out my own mistakes, so if it's not related to my issue or directly preventing me from proceeding, I'll figure it out when I get to it.

You should define TLLPtr as follows:

template<class T>
using TLLPtr = TLLNode<T>*;

And everywhere in the definition of TLL use TLLPtr<T> instead of just TLLPtr (and also change TLLNode to TLLNode<T> ).

Update: I've also noticed that you have TLLNode<T> data; in TLLNode . You can't define a member of the class having the type of class itself, you probably meant T data; .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM