1

I have some classes and a pointer, which class is void*, pointing to one of these classes.

I also have the name of that class in a string variable and I would like to cast that void pointer to that class.

I would like to do something like that:

    string className;

    className = "int";

    (className *) voidPointer;

is there any way to do that??

thank you in advance!

user1089964
  • 87
  • 1
  • 2
  • 8
  • 1
    Possible Duplicate http://stackoverflow.com/questions/582331/is-there-a-way-to-instantiate-objects-from-a-string-holding-their-class-name – Joe Dec 09 '11 at 15:26
  • 2
    What would you possibly do with this? – R. Martinho Fernandes Dec 09 '11 at 15:27
  • C++ is a statically typed language. If you want to do this, you will have to implement your own scheme. The question Joe suggested as a dupe has a few ideas. Voted to close this one. – sbi Dec 09 '11 at 15:31

4 Answers4

2

That is not possible the way you're trying to do.

However, I think boost::any can help you here:

boost::any obj;
if (className == "int")
   obj = (int)voidPointer;
else if (className == "short")
   obj = (short)voidPointer;

//from now you can call obj.type() to know the type of value obj holds
//for example
if(obj.type() == typeid(int))
{
    int value = boost::any_cast<int>(obj);
    std::cout <<"Stored value is int = " << value << std::endl;
}

That is, use boost::any_cast to get the value stored in object of boost::any type.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
1

C++ doesn't have reflection so you cannot do this easily.

What you can do is something on these lines

string classname;
void * ptr;

if ( classname == "Foo" )
{
    Foo* f = static_cast<Foo*> ( ptr );
}
else if ( classname == "Bar" )
{
    Bar* f = static_cast<Bar*> ( ptr );
}
parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85
0

No, you cannot do this. However, you could conceivably use a template class to do this. Note I am providing a solution, but I don't think you should be storing a void* pointer anyway.

template<class T>
T* cast(void* ptr) { return static_cast<T*>(ptr); };

Then, you can do:

int* intPtr = cast<int>(ptr);

I repeat, you probably don't need to be using void* at all.

Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
  • The OP has classnames stored in string. Your solution doesn't cover it – parapura rajkumar Dec 09 '11 at 15:32
  • I am aware of what was in the OP. I don't think he should be doing it at all, but unfortunately we only get a snippet of the over-all problem. Perhaps he wants to cast based on some other "type of" field he has. Perhaps he wants to store different types in a property-type collection. You get my drift? – Moo-Juice Dec 09 '11 at 15:35
0

Sure you can do that:

if (className == "int") {
  int *intPtr = static_cast<int*>(voidPointer);
}

This is not very elegant, though - but you can certainly do that if you must (but there is most probably a better solution to your problem).

cli_hlt
  • 7,072
  • 2
  • 26
  • 22