c++ - 如何动态转换没有虚拟方法的类的指针?
问题描述
我正在使用llvm库,我想检查 llvm::Value * 是否实际上是 llvm::LoadInst *(llvm::LoadInst 是从 llvm::Value 继承的)。
但遗憾的是,llvm::Value 不包含任何虚拟方法!(是的,即使没有虚拟析构函数)是否可以dynamic_cast
在没有虚拟方法的类上使用,或者有没有其他方法来进行类型检查?
解决方案
在 LLVM 中,有一个llvm::dyn_cast<T>
将使用 LLVM 的内部构造从一种类型动态转换为另一种类型,只要它们确实是有效的转换 - 如果您使用错误的 type T
,它将返回 a nullptr
。
所以像:
llvm::Value *v = ... some code here ...
...
llvm::LoadInst* li = llvm::dyn_cast<llvm::LoadInst>(v);
if (!li) { ... not a LoadInst, do whatever you should do here ... }
else { ... use li ... }
自然,如果您已经知道这v
是 a LoadInst
,则无需检查 - 但assert(li && "Expected a LoadInst");
如果您弄错了, an 会发现。
请注意,您不要像使用C++ 标准那样使用T*
for 。llvm::dyn_cast<T>
dynamic_cast
代码中的这条注释llvm::Value
解释了没有 vtable 正是因为这个原因(http://www.llvm.org/doxygen/Value_8h_source.html#l00207)
/// Value's destructor should be virtual by design, but that would require
/// that Value and all of its subclasses have a vtable that effectively
/// duplicates the information in the value ID. As a size optimization, the
/// destructor has been protected, and the caller should manually call
/// deleteValue.
~Value(); // Use deleteValue() to delete a generic Value.
推荐阅读
- sql - 正确使用 PERCENTILE_CONT - Oracle SQL
- c# - 如何在基于 .NET Framework 4.6.1 构建的单元测试项目中添加 .NET Core 2.1 项目引用
- xml - XSL 转换错误 - 未定义命名空间前缀
- react-native - 在反应本机中使用不同用户登录时更新导航抽屉中的用户名
- java - java.lang.IllegalStateException: Fragment 尚未附加 Android Studio
- c# - Asp.Net Core 中的运行时更改连接字符串
- nativescript - 构建 nativescript-vue 项目时无法读取未定义的属性“env”
- visual-studio-code - 使用 ctrl 向上或向下滚动将光标移动到第一个非空白
- python - pandas:如何获得第一个正数?
- node.js - 尝试使用 nodejs 中的 cloudconvert-api 在 s3 上将 docx 转换为 pdf