Friday 15 February 2013

pointers - How to make make a variable undetermined type in c++? -



pointers - How to make make a variable undetermined type in c++? -

for illustration have node contains

node * next; [x] data;

how fill in [x] can create 'data' either types a, b, c, d, determine later on. tried making void, lead errors. using have linked list holding 1 variable, of types b c d.

you can either utilize templates, or void pointers (and should never utilize void pointers in c++ when templates trick).

template <typename t> struct node { node * next; t data; };

now node<int> , node<float> different types. can utilize any type argument, long type can default-constructed. if want restrict t 1 of set of types reply bit more involved, there no reason this.

if, on other hand, want single linked list able hold many different types t has able represent of types. illustration if of types want store derive mutual class a utilize node<std::unique_ptr<a>> , able store a or more-derived-subtype of a in particular list.

if want 1 single list able hold elements of of set of unrelated types, need build "variant" construction capable of storing of them, field indicating type holds, utilize variant construction type argument node.

if want 1 single list able hold elements of any type @ all don't have many options besides using void pointer data: node<void *>. there many caveats technique, deciding owns pointed-to allocations, , figuring out right way delete them.

(note though wrote node * next, next node<t> *. within node class, template arguments implied.)

c++ pointers linked-list nodes

No comments:

Post a Comment