My goal is to create a linked list with nodes of different types. For this, I created a node class template as follows:
template <class T>
class N_Node
{
public:
N_Node(T e, N_Node *p = nullptr ,N_Node *n = nullptr);
void set_previous(N_Node<T> *p);
void set_next(N_Node<T> *n);
N_Node get_previous();
N_Node get_next();
T element;
N_Node *prev;
N_Node *next;
};
Now, in the main.cpp, when i try to do the following, it gives me an error saying argument of type N_Node<int>* is incompatible with parameter of type N_Node<char>*. So, I was wondering if there is any way to specify that the node set as the previous can be of a different type to the current node?
N_Node<int> n1(5);
N_Node<char> n3('g');
n3.set_previous(&n1);
Absolutely, create a
N_Node_Baseclass that omits theelementmember, and inherit from it forN_Node<T>. Most C++ standard library implementations do this to reduce template overhead.Of course, by doing this you’ll lose the ability to traverse the list and access elements because you won’t know the type of each element. You might want to type-erase past a minimal interface for
Tusing e.g.boost::any, but you’ll have to say more about why you want to do this.