Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out Type of C++ Void Pointer

I have a small question: how do I find out what type a C++ pointer is?

I often use a small function in my console programs to gather input, which looks something like this:

void query(string what-to-ask, [insert datatype here] * input)

I would like to create a generic form, using a void pointer, but I can't cin a void pointer, so how to I find out it's type so I can cast it?

like image 403
new123456 Avatar asked Nov 11 '09 22:11

new123456


2 Answers

If you control the datatype yourself, I would probably make a class/struct that contains an enum of all of the data types you care about and pass that. You could then query the passed in pointer for it's datatype, and then cast appropriately.

IE ( pseudo code warning - treating this as a struct for now. )

class MyDataType {
     enum aDataType type;
     void * myData;
}

void query( string whatToAsk, MyDataType * pdata)
{
    switch ( pdata.type) {
        case integer:
              int * workInt = (int * )  pdata;
              do whatever you want to to get the data
              break;
        case someFunkyObject:
              someFunkyObject pob = (SomeFunkyObject *) pdata;
              Do whatever you want with the data.

        etc.
    }
}
like image 173
John Chenault Avatar answered Oct 05 '22 03:10

John Chenault


You can't.

However, one alternative is to do away with void pointers, make everything derive from a common base class and use RTTI.

An example:

class Base
{
public:
   virtual ~Base() {}
};

class Foo : public Base { /* ... */ };

void SomeFunction(Base *obj)
{
    Foo *p = dynamic_cast<Foo*>(obj);
    if (p)
    {
        // This is of type Foo, do something with it...
    }
}
like image 20
asveikau Avatar answered Oct 05 '22 05:10

asveikau