强制转换为仅在运行时知道的类型 [英] Cast to type known only at runtime

查看:109
本文介绍了强制转换为仅在运行时知道的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下内容:

void *pA;

现在,我希望在运行时将此指针转换为编译时未知的类型.也就是说,什么是等效项或如何在ANSI C中模拟c ++ dynamic_cast?

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 ?

谢谢!

推荐答案

现在,我希望在运行时将此指针转换为编译时未知的类型.也就是说,什么是等效项或如何在ANSI C中模拟c ++ dynamic_cast?

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 ?

好吧,这不是dynamic_cast所做的.您不能转换为在编译时未知的类型.

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

如果您需要根据各种条件在执行程序期间将对象转换为可能会更改的类型,那么它就像创建一个检查某些变量的switch语句一样简单(并且枚举值(无论是哪种值)来确定要执行的强制类型转换.然后可以使用已知类型.

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.

这篇关于强制转换为仅在运行时知道的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆