如何在Clang中判断给定QualType是否包含指针类型
Clang 内置了 TypeVisitor 框架专门处理类型遍历需求,无需手动枚举所有类型分支,可以完整覆盖所有内置、自定义、模板类型场景,实现代码如下:
核心实现
#include "clang/AST/TypeVisitor.h" #include "clang/AST/Decl.h" #include "clang/AST/Type.h" using namespace clang; class HasPointerDetector : public TypeVisitor<HasPointerDetector, bool> { public: // 匹配普通指针类型,直接返回true bool VisitPointerType(const PointerType* PT) { return true; } // 匹配成员指针类型(如 int Class::*),不需要识别时可修改返回false bool VisitMemberPointerType(const MemberPointerType* MPT) { return true; } // 处理struct/union/class类型,遍历所有成员变量的类型 bool VisitRecordType(const RecordType* RT) { const RecordDecl* RD = RT->getDecl(); for (const FieldDecl* Field : RD->fields()) { if (Visit(Field->getType().getTypePtr())) { return true; } } return false; } // 处理模板特化类型,遍历所有模板实参的类型 bool VisitTemplateSpecializationType(const TemplateSpecializationType* TST) { for (const TemplateArgument& Arg : TST->template_arguments()) { if (Arg.getKind() == TemplateArgument::Type && Visit(Arg.getAsType().getTypePtr())) { return true; } } // 处理模板别名场景 if (TST->isTypeAlias()) { return Visit(TST->getAliasedType().getTypePtr()); } return false; } // 处理数组类型,遍历元素类型 bool VisitArrayType(const ArrayType* AT) { return Visit(AT->getElementType().getTypePtr()); } // 处理typedef/using定义的别名类型,遍历底层实际类型 bool VisitTypedefType(const TypedefType* TT) { return Visit(TT->getDecl()->getUnderlyingType().getTypePtr()); } // 处理带命名空间/限定符的类型(如 ns::MyType),遍历实际指向的类型 bool VisitElaboratedType(const ElaboratedType* ET) { return Visit(ET->getNamedType().getTypePtr()); } // 处理左值/右值引用类型,遍历被引用的类型 bool VisitLValueReferenceType(const LValueReferenceType* RT) { return Visit(RT->getPointeeType().getTypePtr()); } bool VisitRValueReferenceType(const RValueReferenceType* RT) { return Visit(RT->getPointeeType().getTypePtr()); } // 所有未匹配到的默认类型返回false bool VisitType(const Type* T) { return false; } };
调用方法
bool hasPointerType(QualType type) { // 先获取规范类型并去掉cv限定符,避免别名、限定符干扰检测 QualType canonicalType = type.getCanonicalType().getUnqualifiedType(); HasPointerDetector detector; return detector.Visit(canonicalType.getTypePtr()); }
注意事项
- 如果需要识别
std::shared_ptr、std::unique_ptr等包装了指针的自定义类型,可以在VisitRecordType中补充对类型名的判断逻辑,匹配到智能指针类型直接返回true即可 - 上述实现已经覆盖了C/C++绝大多数常用类型场景,
TypeVisitor框架会自动处理所有类型的分发逻辑,无需手动补全所有Type子类的分支
内容的提问来源于stack exchange,提问作者D Asp
相关产品推荐
相关产品推荐

