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?
views:
47answers:
4
A:
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
Luca Matteis
2010-07-15 15:57:21
A:
You should have a look at C++ templates. This way you can design classes or functions to work on any data type.
codymanix
2010-07-15 16:06:43
+1
A:
There are various options, listed here from the safest to the most difficult to manage
- A common base class
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.
Matthieu M.
2010-07-15 16:14:09