tags:

views:

47

answers:

4

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?

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
+2  A: 

You could have a stack of boost::any values.

Anthony Williams
A: 

You should have a look at C++ templates. This way you can design classes or functions to work on any data type.

codymanix
+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.