如何在 Clang 中获取模板化类的实例化 CXXRecordDecl?
How do you obtain the instantiated CXXRecordDecl of a templated class in Clang?
例如,我有一个类:
template<typename T>
class Foo {
public:
T getBar();
private:
T bar_;
};
它实例化为:
using FooBarT = Foo<Bar>;
如何获取具有已解析字段和方法Foo<bar>
CXXRecordDecl
?
我试过了:
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'
这对我有用:
- 演员
ClassTemplateSpecializationDecl
到DeclContext
, - 使用
DeclContext::decls()
遍历存储的声明, dyn_cast
迭代Decl
s 到FieldDecl
和getType()
- 这将是成员变量的实例化类型。dyn_cast
为成员功能CXXMethodDecl
并继续类似 - 我没有 得自己尝试一下。
所有这些都是通过逐步学习和研究ASTDumper
如何工作的。
相关文章:
- 从C++实例化QML
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 约束和显式模板实例化
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 对象实例化调用构造函数的次数太多
- 如何使用非默认构造函数实例化模板化类
- 静态数据成员模板专用化的实例化点在哪里
- 错误的cv::face FacemarkLBF实例化
- C++的解析器在可以区分比较和模板实例化之前会做什么?
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- 检查某些类型是否是模板类 std::optional 的实例化
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 无法使用 SWIG 在 Python 中实例化C++类(获取属性错误)
- 模板化类构造函数的模板实例化
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 受约束的成员函数和显式模板实例化
- 对显式实例化的模板函数的未定义引用
- [temp.variadic]中关于包扩展实例化的措辞