Hya,
Lemme explain my point.
template<typename T>
class node{
T data;
template<typename X>
node<X>* right; // can point to any node<typename> i know its wrong
}
so that i can do something like:
node<int> a;
a.data = 23;
node<float> b;
b.data =43.6;
a.right= b;
std::cout<< a.data <<a.right->data;
Another example:
template <class Type>
struct vnode {
Type data;
vnode<Type> * vnodenext;
// vrow what_to_put_here // **i don't want to use void ptrs neither want to cast back manually**
}
And in main function if I define vnode struct of type string and another vnode of type int, then what pointer def should I replace with vrow in vnode struct definition so that it can point to vnode of type int or other type of vnode? e.g.
vnode<string> mystring;
vnode<int> myint;
myint.vrow = &mystring
It isn’t really possible to do what you want because when using templates you have to know the types involved at compile time. In contrast, walking a previously constructed linked list requires you to discover the types in the list at runtime.
To illustrate, consider this:
Now you can certainly have a list of
node_base*, and those nodes can contain any type of data that you want. Constructing the list is not a problem, since at the point you add nodes the static type ofdatais known and you can create anode<TData>.Now the problem is how to get the data back. Assume that there’s a function that returns the data inside a node, given a pointer to that node. What should be the functions return type? Clearly (unless you know from beforehand that all data types share a common base) there is no single type that can be returned. That leaves you with:
void*However, #2 is not feasible in practice (although it works in theory). You cannot write the data type as a template argument because that would require you to know it at compile time, which defeats the purpose of a multi-data-type list.
Therefore, the only solution left is returning a pointer type (either a
node_base*or avoid*to the data itself) and then casting that pointer to a useful type using some mechanism.