强制转换为仅在运行时知道的类型

编程入门 行业动态 更新时间:2024-10-26 14:38:22
本文介绍了强制转换为仅在运行时知道的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有以下内容:

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.

更多推荐

强制转换为仅在运行时知道的类型

本文发布于:2023-10-14 21:41:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492291.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!