Convert nullity * to a dynamic type

I have a double variable i
, that is converted to a void pointer named pointer
:

double i = 3;
 void *pointer = &i;

When I like to convert the void pointer back to double I used:

double p = *((double*) pointer);

I would like to convert the void pointer to the type I will send as a char*:

char* myType= typeid(i).name();//get the name of type of "i"
 int p = *((myType*) pointer); // how to implement?

Is it possible?

instead of

char* myType= typeid(i).name();//get the name of type of "i"
int p = *((myType*) pointer); // how to implement?

use

typedef decltype(i) myType;
myType p = *((myType*) pointer);

or better:

typedef decltype(i) myType;
auto p = *reinterpret_cast(pointer);

Works with c++11 or later. If you want to decltype
on older c++ compilers, it is emulated in boost.

Edit.This is probably different from what you wanted to do, which I suppose is something like this:

void myFunction(void* unknownParam) {
    typedef (realTypeOf unknownParam) RealType; // <-- this is not real c++
    RealType &a = *reinterpret_cast(unknownParam)
    //do stuff using 'a'
}

This is not possible in C++, but there is a reason: it doesn’t make much sense. And the reason is that for myFunction
to be valid the //do stuff using 'a'
part should be valid for whatever type RealType
ends up being. As such, it cannot rely on any feature the RealType
type have: it cannot use any of its methods, it cannot use any operator, it cannot even know whether it is a class or not. Basically, you cannot do anything more with it than what you would already be able to do on a void*
, so giving the type a name doesn’t really help you much.

A language feature that is similar to what you want (but not quite it) is type reflection, which is not present in C++, but you can find it in language such as Java, Objective-C or C#. Basically, you ask the object itself if it has a certain method, and eventually call it. An example in Objective-C

-(void)myFunction:(id)unknownParam {
    if([unknownParam respondsToSelector:@selector(myMethod)])
        [unknownParam performSelector:@selector(myMethod)]
}
Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Convert nullity &ast; to a dynamic type

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录