Cast to type known only at runtime

跟風遠走 提交于 2019-12-24 00:59:22

问题


let's say I have the following :

void *pA;

now I want at runtime to convert this pointer to a type that is not known at compile time. i.e. what is the equivalent or how to emulate in ANSI C a c++ dynamic_cast ?

Thanks !


回答1:


now I want at runtime to convert this pointer to a type that is not known at compile time. i.e. what is the equivalent or how to emulate in ANSI C a c++ dynamic_cast ?

Well, that's not what dynamic_cast does. You cannot cast to a type which is not known at compile time.

If you need to cast the object to a type which may change during the execution of your program depending on various conditions then it can be as simple as creating a switch statement which checks some variable (and enumerated value, whatever) to determine which cast to perform. It can then work with the known type.


On a side note, it would be advantageous for you to describe your high level problem instead of how to implement your proposed solution (which may or may not make sense). There may exist alternatives to your approach which will be better than what you have envisioned, but we can't offer any without knowing what problem you are taking a stab at solving.




回答2:


Something like this might work:

void get_val(void * buf, void *data, int type_id) {
  switch (type_id) {
    case INT: int *sp = (int*)data;
              int *dp = (int*)buf;
              *dp = *sp; 
              // or just *((int*)buf) = *((int*)data)
              break;
    case FLOAT:float *sp = (float*)data;
               float *dp = (float*)buf;
               *dp = *sp; 
               break;
   /* ... */
  }
}


来源:https://stackoverflow.com/questions/12323589/cast-to-type-known-only-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!