jeudi 27 juin 2019

How to get the actual type of a template typed class member with Clang?

For example, I have the following class:

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

private:
    T bar_;
};

It is instantiated as:

Foo<Bar> foo;

I extract the clang::CXXRecordDecl node of class Foo, and iterate through its fields:

for (const clang::FieldDecl *fieldDecl: fooRecordDecl->fields()) {
    // fieldDecl->getType() gives T
    // fieldDecl->getNameAsString() gives bar_
}

I want something that does fieldDecl->getInstantiatedType() that gives Bar

I understand that the AST for the CXXRecordDecl of Foo shouldn't contain any information on the instantiated type. I was wondering if this linking information was stored somewhere else in the AST, and how I could retrieve it.


My current solution involves getting uninitialized template parameters in order, say {A, B, C} for template<typename A, typename B, typename C> class Baz {}; and storing them in an std::vector. Then finding the instantiation call Baz<Foo, Bar, Baz>, and store the instantiated types in order in another std::vector, and link them together by index to get:

{ A: Foo, B: Bar, C: Baz}

This seems very convoluted and "un-Clang" like.

Aucun commentaire:

Enregistrer un commentaire