user1089964
user1089964

Reputation: 87

How could I cast to a variable class name?

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!

Upvotes: 1

Views: 1209

Answers (4)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361532

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.

Upvotes: 2

cli_hlt
cli_hlt

Reputation: 7164

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).

Upvotes: 0

Moo-Juice
Moo-Juice

Reputation: 38800

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.

Upvotes: 0

parapura rajkumar
parapura rajkumar

Reputation: 24403

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 );
}

Upvotes: 1

Related Questions