Declare and define a new class named "Object":
class Object
{
private: const void *pointer
const char *type;
public: template <class T> Object(const T *t)
{
this->pointer = t;
this->type = typeid(*t).name();
//NOTE that you must #include <typeinfo.h> in order to use the "typeid" keyword of course!
}
const void* GetPointer()
{
return this->pointer;
}
const char* GetType()
{
return this->type;
}
template <class T> const T* GetPointer()
{
return (T*)this->pointer;
}
template <class T> T& GetReference()
{
return *(T*)this->pointer;
}
template <class T> T GetValue()
{
return *(T*)this->pointer;
}
//You also can add some explicit and/or implicit conversions operators if you want by using template class in each
};
Then replace your void*
with Object
in your list.
Each time you iterate this list, first call the GetType
function of the Object
class to know the type of the object that the void pointer of this Object
points at. GetType
returns the name of this type as const char*
string.
You can use the strcmp
function to help you compare const char*
strings.
Then after that you called GetType
function, now you know to which type to convert or cast the void pointer of the Object
and then do whatever you want with the current iterated object!
Call one of the two overloads of the GetPointer
function to retrieve the void pointer of the Object
converted / casted or not.
If you just want the reference to the object that the void pointer of the Object
points at, then just call the GetReference
function instead GetPointer
.
Hope if you like my answer!
typeid
is for polymorphic types, notvoid*
. – Godmother