Reputation: 4169
I have seen stack class that uses the template to define the type of data the stack hold. What if I want a stack that hold different type of data? I have a little thought into it and come close to using void pointer (but void pointer can't be dereferenced, so it is not the correct solution) So... Is it possible to have such a class?
Upvotes: 0
Views: 111
Reputation: 300119
There are various options, listed here from the safest to the most difficult to manage
boost::variant
(assuming you know all types beforehand)boost::any
(very difficult to act on, since anything can be in there...)void*
(very difficult once more and there is a memory management issue)Pick up the one you wish.
Upvotes: 1
Reputation: 29508
You should have a look at C++ templates. This way you can design classes or functions to work on any data type.
Upvotes: 0
Reputation: 29267
void pointers can't be dereferenced, sure, but you can still cast the void pointer to the actual type of pointer you need, and then dereference it.
void *ptr = malloc(10);
*ptr = 10; // won't work
*((int *)ptr) = 10; // will work
Upvotes: 0