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

What is the purpose of method classof in clang?

本文关键字:是什么 方法 classof clang      更新时间:2023-10-16

让我给你一个例子来解释我想做什么(或者至少知道这是可能做到的):

在Clang中,让我们取一些基本的ValueDecl。从提供的链接中可以看到,这个ValueDecl可以:
  • 是一个简单的ValueDecl
  • 做一个DeclaratorDecl
  • 为EnumConstantDecl
  • 成为一个间接字段decl
  • 为UnresolvedValueDecl

我想知道,给定一个ValueDecl *,我是否可以确定它是否是上面列出的类之一,或者我是否被限制在这个ValueDecl * ?

在每个类中,都有这个bool classof()方法,但是我不明白这个方法的目的。这能解决我的问题吗

classof确实是解决方案的一部分,但通常不意味着直接使用。

相反,你应该使用isa<>, cast<>dyn_cast<>模板。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<>不允许空参数,如果参数可能为空,可以使用cast_or_null<>dyn_cast_or_null<>


要进一步了解没有virtual方法的多态性设计,请参阅LLVM isa<>是如何实现的,您将注意到它在幕后使用classof