例如,我有一个课:

template<typename T>
class Foo {
public:
    T getBar();

private:
    T bar_;
};

实例化为:
using FooBarT = Foo<Bar>;

如何获取带有CXXRecordDecl的已解析字段和方法的Foo<bar>

我试过了:
const auto *typeAliasDecl = llvm::dyn_cast<clang::TypeAliasDecl>(decl);
typeAliasDecl->getUnderlyingType()->getAsCXXRecordDecl()->dump();

我得到的输出是:
ClassTemplateSpecializationDecl 0x0000000 class Foo
`-TemplateArgument type 'Bar'

但是,我也想要带有字段和方法的CXXRecordDecl,以便我可以遍历它们。我也尝试过:
for (const auto *contextDecl: typeAliasDecl->getUnderlyingType()->getUnqualifiedDesugaredType()->getAsCXXRecordDecl()->getDeclContext()->decls()) {
    const auto *classTemplateDecl = llvm::dyn_cast<clang::ClassTemplateDecl>(contextDecl);
    classTemplateDecl->dump();
}

输出:
ClassTemplateDecl Foo
|-TemplateTypeParmDecl 0x0000000 referenced typename depth 0 index 0 T
|-CXXRecordDecl class Foo definition
| ...
| |-FieldDecl 0x0000000 referenced bar_ 'T'
|-ClassTemplateSpecializationDecl 0x0000000 class Foo
  `-TemplateArgument type 'Bar'

如您所见,CXXRecordDecl class Foo definition可以访问FieldDecl,但是不知道bar_的类型实例化,而ClassTemplateSpecializationDecl可以。

我想要具有CXXRecordDecl的实例化类型的FieldDecl bar_

最佳答案

仅供引用,您想要的CXXRecordDecl只是AST中的ClassTemplateSpecializationDecl,因为ClassTemplateSpecializationDecl是CXXRecordDecl的子类。您真正想要的不是您已经拥有的CXXRecordDecl,而是该CXXRecordDecl中的FieldDecl。

您在ClassTemplateSpecializationDecl下没有FieldDecl的原因是您的模板实例化代码不使用bar_。尝试以下来源:

template<typename T>
class Foo {
public:
    T getBar() { return bar_; };

private:
    T bar_;
};
using FooBarT = Foo<int>;
void func() {
    FooBarT().getBar();
}

然后,FieldDecl将在ClassTemplateSpecializationDecl下:
| `-ClassTemplateSpecializationDecl 0x1fe7f2a9d80 <line:2:1, line:9:1> line:3:7 class Foo definition
...
|   |-FieldDecl 0x1fe7f2aa3c8 <line:8:2, col:4> col:4 referenced bar_ 'int':'int'

10-04 22:19