clang中方法类的目的是什么?

时间:2014-08-14 08:13:46

标签: c++ clang

让我举个例子来解释一下我想做什么(或者至少知道这是否可以做到):

在Clang中,让我们采取一些基本的ValueDecl。正如您在提供的链接上看到的那样,ValueDecl可以:

我想知道,如果给定ValueDecl *,我可以确定它是否是上面列出的类别之一,还是我受限于ValueDecl *

在每个班级中,都有bool classof()方法,但我不了解此方法的用途。它可以解决我的问题吗?

1 个答案:

答案 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

相关问题