user385261
user385261

Reputation: 4169

Is it possible to create stack class that take any type of variable? not only 1 type

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

Answers (4)

Matthieu M.
Matthieu M.

Reputation: 300119

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.

Upvotes: 1

codymanix
codymanix

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

Luca Matteis
Luca Matteis

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

Anthony Williams
Anthony Williams

Reputation: 68641

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

Upvotes: 2

Related Questions