3

例如,我有一堂课:

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_

4

2 回答 2

2

仅供参考,您想要的 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'
于 2019-12-31T02:45:10.483 回答
1

这对我有用:

  1. 投到, ClassTemplateSpecializationDecl_DeclContext
  2. DeclContext::decls()用,遍历存储的声明
  3. dyn_cast迭代DeclFieldDecland getType()- 这将是成员变量的实例化类型。
  4. dyn_castCXXMethodDecl成员函数并以类似方式继续 - 我不必为自己尝试它。

所有这一切都是我通过逐步了解并研究其ASTDumper工作原理而学到的。

于 2019-07-03T13:44:51.977 回答