hya,
lemme explain point .
template<typename t> class node{ t data; template<typename x> node<x>* right; // can point node<typename> know wrong }
so can :
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 use void ptrs neither want cast manually** }
and in main function if define vnode struct of type type string , vnode of int ,then pointer def should replace vrow in vnode struct definition , can point vnode of type int or other type of vnode e.g
vnode<string> mystring; vnode<int> myint; myint.vrow = &mystring
thanks alot)
it isn't possible want because when using templates you have know types involved @ compile time. in contrast, walking constructed linked list requires discover types in list @ runtime.
to illustrate, consider this:
struct node_base { virtual ~node_base() {} } template<typename t> struct node : public node_base { t data; node_base* right; }
now can have list of node_base*
, , nodes can contain type of data want. constructing list not problem, since @ point add nodes static type of data
known , can create node<tdata>
.
now problem how data back. assume there's function returns data inside node, given pointer node. should functions return type? (unless know beforehand data types share common base) there no single type can returned. leaves with:
- returning
void*
- writing templated function receives data type argument
however, #2 not feasible in practice (although works in theory). cannot write data type template argument because require know @ compile time, defeats purpose of multi-data-type list.
therefore, solution left returning pointer type (either node_base*
or void*
data itself) , casting pointer useful type using mechanism.
Comments
Post a Comment