让我举个例子来解释一下我想做什么(或者至少知道这是否可以做到):
在Clang中,让我们采取一些基本的ValueDecl。正如您在提供的链接上看到的那样,ValueDecl
可以:
ValueDecl
我想知道,如果给定ValueDecl *
,我可以确定它是否是上面列出的类别之一,还是我受限于ValueDecl *
?
在每个班级中,都有bool classof()方法,但我不了解此方法的用途。它可以解决我的问题吗?
答案 0 :(得分:3)
classof
确实是解决方案的一部分,但通常不用于直接使用。
相反,您应该使用isa<>
, cast<>
and dyn_cast<>
templates。 LLVM程序员手册中的一个例子:
static bool isLoopInvariant(const Value *V, const Loop *L) {
if (isa<Constant>(V) || isa<Argument>(V) || isa<GlobalValue>(V))
return true;
// Otherwise, it must be an instruction...
return !L->contains(cast<Instruction>(V)->getParent());
}
cast<>
和dyn_cast<>
之间的区别在于,如果实例无法转换,前者断言,而前者仅返回空指针。
注意:cast<>
和dyn_cast<>
不允许使用null参数,如果参数可能为null,则可以使用cast_or_null<>
和dyn_cast_or_null<>
。
有关不使用virtual
方法的多态性设计的进一步见解,请参阅How is LLVM isa<>
implemented,您会注意到它在幕后使用classof
。