对于 Decl,有 getASTContext(),但是作为 Decl 的 AST 节点,为什么 Expr 没有这样的功能以及如何从 Expr 中获取 ASTContext?
注意:Decl 是https://clang.llvm.org/doxygen/classclang_1_1Decl.html,Expr 是https://clang.llvm.org/doxygen/classclang_1_1Expr.html
对于 Decl,有 getASTContext(),但是作为 Decl 的 AST 节点,为什么 Expr 没有这样的功能以及如何从 Expr 中获取 ASTContext?
注意:Decl 是https://clang.llvm.org/doxygen/classclang_1_1Decl.html,Expr 是https://clang.llvm.org/doxygen/classclang_1_1Expr.html
没有直接的方法可以从 Expr 或 Type 中获取 ASTContext;仅来自 Decl。但是,您可以通过向下转换到子类型然后从子类型获取 Decl 从 Expr 通过 Type 获取 ASTContext。
例如:
clang::QualType QualType = Expr->getType();
const clang::Type* Type = QualType.getTypePtr();
const clang::DecltypeType* Decltype =
static_cast<const clang::DecltypeType*>(Type);
const clang::Decl* Decl = Decltype->getAs<clang::Decl>();
const clang::ASTContext& Context = Decl->getASTContext();
当然,这并不总是有效,因为并非所有类型都是 Decl-Types。