Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data structure that can hold multiple types of data

Like the title says, I'm looking for some kind of data structure which will allow me to store any type of class into it that I need at the time. For example:

Foo *foo = new Foo();
Bar *bar = new Bar();
someContainer.push_back( foo );
someContainer.push_back( bar );
someContainer.access( 0 )->doFooStuff();
someContainer.access( 1 )->doBarStuff();

Ideally, as I showed there, it would also allow me to access the contents and use their functions/etc.
I want one of these as I am attempting to create an "invisible" memory management system that just requires a class to inherit my memory manager class, and everything will work automagically.
Here is an example of what I want the code to look like:

template< class T >
class MemoryManaged
{
   MemoryManaged()
   {
      container.push_back( this );
   }
   void *operator new()
   {
       // new would probably be overloaded for reference counting etc.
   }
   void operator delete( void *object )
   {
       // delete would most definitely overloaded
   }
   T &operator=( T &other )
   {
      // = overloaded for reference counting and pointer management
   }

   static SomeContainer container;
}

class SomeClass : public MemoryManaged< SomeClass >
{
   // some kind of stuff for the class to work
};
class AnotherClass : public MemoryManaged< AnotherClass >
{
   // more stuff!
};

I hope that my code helps make clear what exactly it is I want to do. If someone knows some kind of already-built data structure that would allow me to do this, that would be awesome. Otherwise, I am currently working on building some kind of shambling zombie of a linked list class that uses templated nodes in order to link any type of class to any other type of class. I still have no idea how I'd get it to work yet, and I would love to be spared the blood, sweat, and tears (and hair) it would take to figure out how to make it work.

like image 737
Freezerburn Avatar asked Feb 26 '23 17:02

Freezerburn


2 Answers

Have a common base class for all of your multiple types. Have the data structure hold onto pointers of your base class's type.

like image 103
Gunslinger47 Avatar answered Mar 06 '23 19:03

Gunslinger47


Take a look at boost::any and boost::variant.

like image 45
Nikolai Fetissov Avatar answered Mar 06 '23 19:03

Nikolai Fetissov