Jump to content

Avoid using void* and typecast...


cyberium

Recommended Posts

Hi,

Considering struct like this :

struct myData
{
   int         myInt;
   bool        myBool;

   someType    data;

   myData(const int& intValue, const bool& boolValue, const someType& dataValue)
   {
       myInt = intValue;
       myBool = boolValue;
       data = dataValue;
   }
}

std::list < myData > myList;

...

main
{
   myData* d = new myData(5, true, 1);
   myList.push_back(d);
   myData* d = new myData(5, true, "hello");
   myList.push_back(d);
   ...
}

Idea is to have multiple type of data possible in same List.

Is it possible to realise this without using void*?

Link to comment
Share on other sites

you can use union to hold multiple data in same list

One bad thing using union is constructor will be called for all type i declare on it.

I probably can do some workaround by using only pointer to type but this require like void* method to handle new and delete for that data.

see boost::any

boost::any seem to be realy polyvalent but need boost lib...

Iam doing some test with new class containing template but no good result for now...

Link to comment
Share on other sites

You can either common parent class if you use inheritance, which isn't that trivial in c++.

You see, since c++ isn't real level 3 OO language, it do not support things like common inheritance root. Like object in java. Actually, java used to store objects in all its datastores before it had templating.

back to c++ ...

The real problem with storing void*, is that you don't know what type they are.

One way it is "solved" in c++, is by having wrapper class, that holds void* and "type" variable. You store wrapper classes in your collection. When you pull it from it, you check the type, and upcast accordingly.

Really easy to implement, or you can just use ready one, just like darkstalker suggested.

Link to comment
Share on other sites

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. Privacy Policy Terms of Use