I have a template class Tripla (node for a list structure) and another template class Lista. I want to make them generic so they can reused in the future, however I'm not sure how to set the data type to the Tripla objects from the class Lista.
template <class T>
class Tripla
{
public:
T element;
Tripla *anterior;
Tripla *siguente;
Tripla();
.................other functions/procedures
};
template <class T>
class Lista
{
private:
Tripla<T> *primer; // or would this simple be Tripla *primer??
Tripla<T> *ultimo;
public:
Lista();
~Lista();
void insertar_principio(T);
void menu();
.................other functions/procedures
};
template <class T>
void Lista<T>::insertar_principio(T el)
{
if (primer == NULL)
{
primer = new Tripla<T>; // would this be primer = new Tripla??
ultimo = primer;
primer->element=el;
}
else
{
Tripla<T> *aux = primer; // would this be Tripla *aux = primer??
primer = new Tripla;
primer->element = el;
aux->anterior = primer;
primer->siguente = aux;
}
}
Some compilation errors include not being able to convert Tripla*
to Tripla<T>*
and "error C2955: 'Tripla' : use of class template requires template argument list".
I am having problems understanding how to set the same data type to both. For example, from main.cpp, I want to have something like
Lista list<int>.menu()
and that will automatically make Tripla *primer and *ultimo work with int.
You are missing some template arguments in some places. First of all:
Tripla *anterior;
Tripla *siguente;
should be:
Tripla<T> *anterior;
Tripla<T> *siguente;
And then:
primer = new Tripla;
should be:
primer = new Tripla<T>;
Also notice that there already exist a linked list (and even doubly linked list) implementation in the standard library: std::forward_list
for singly linked lists and std::list
for doubly linked list.