简体   繁体   中英

How can I link Nodes of two different types? (templated classes)

I'm making a templated class that consists of two binary search trees that are linked together. For example, a tree of strings and a tree of ints.

However, I'm having trouble with creating the link.

What I have for the nodes:

template <class T>
class Node {

T data;
Node* link;
Node* left;
Node* right;

}

if I call

Node<string> newstring = new Node<string>();
Node<int> newint = new Node<int>();
newstring -> link = newint;
newint -> link = newstring;

i'll get

error: cannot convert ‘Node<int>*’ to ‘Node<std::basic_string<char> >*
error: cannot convert ‘Node<std::basic_string<char> >* to ‘Node<int>*’

How can I link Nodes of two different types?

You can achieve it by a base class:

class BaseNode {
};

template <class T>
class Node : public BaseNode {
public:
    BaseNode * link;
    BaseNode * left;
    BaseNode * right;
};

and then

Node<string> * newstring = new Node<string>();
Node<int> * newint = new Node<int>();
newstring -> link = newint;
newint -> link = newstring;

Maybe you need to add some code to identify what is the real type of the pointer points to. It should be a design problem.

I'll look into base classes.

It looks like the design for Node is faulty. I might do something like

template <class T, class S>
class Node {

T data;
Node<S,T>* link;
Node<T,S>* left;
Node<T,S>* right;

}

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