How do I typecast with type_info?

15.9k Views Asked by At

I've stored a pointer to a type_info object.

int MyVariable = 123;
const std::type_info* Datatype = &typeid(MyVariable);

How might I use this to typecast another variable to that type? I tried this, but it doesn't work:

std::cout << ((*Datatype)3.14) << std::endl;

Using the function form of typecasting doesn't work, either:

std::cout << (*Datatype(3.14)) << std::endl;
4

There are 4 best solutions below

4
On BEST ANSWER

I don't think such casting can be done. Suppose you could do "dynamic" casting like this at runtime (not to mean dynamic_cast). Then if you used the result of the cast to call a function the compiler could no longer do type checking on the parameters and you could invoke a function call that doesn't actually exist.

Therefore it's not possible for this to work.

3
On

Simply you cannot do that using type_info. Also, in your example DataType is not a type, it's a pointer to an object of type type_info. You cannot use it to cast. Casting requires type, not pointer or object!


In C++0x, you can do this however,

    int MyVariable = 123;

    cout << (decltype(MyVariable))3.14 << endl;

    cout << static_cast<decltype(MyVariable)>(3.14) << endl;

Output:

3
3

Online Demo: http://www.ideone.com/ViM2w

0
On

Typecasting isn't a run-time process, it's a compile-time process at least for the type you're casting to. I don't think it can be done.

0
On

If you're willing to use fragile, GCC-specific logic, take a look at the __dynamic_cast and __do_upcast methods. These approximately correspond to dynamic_cast<> and static_cast<> and can be used to cast void * pointers for which you have the std::type_info.