How do I get the base class from this example using Clang?
Here is a very basic code example and what I would like to have:
class B{
// Implementation of class B
};
class D : public B{
// Implementation of class D
};
int main(){
try{
// Code for try statement
}
catch(D & d){
// Handler for D
}
catch(B & b){
// Handler for B
}
return 0;
}
Currently I can get the CXXRecordDecl of class B and class D in handlers (I can get them from getCaughtType
in class CXXCatchStmt
).
I would like to access CXXRecordDecl
class B from class D, as we have class D : public B
.
I have tried the following methods available class CXXRecordDecl
on mine CXXRecordDecl
from class D
:
- getCanonicalDecl () : returns class D
- getInstantiatedFromMemberClass () : returns nullptr
- getDefinition () : returns class D
Now I have no ideas. Anyone have an idea?
source to share
Here is an implementation of the answer given by Joachim Pileborg in the comments.
bool VisitCXXTryStmt(CXXTryStmt * tryStmt){
int nbCatch = tryStmt->getNumHandlers();
for(int i = 0 ; i < nbCatch ; i++){
if(tryStmt->getHandler(i)->getCaughtType().getTypePtr()->getPointeeCXXRecordDecl() == nullptr){
cout << "The caught type is not a class" << endl;
}
else{
cout << "Class caught : " << tryStmt->getHandler(i)->getCaughtType().getTypePtr()->getPointeeCXXRecordDecl()->getNameAsString() << endl;
}
if(tryStmt->getHandler(i)->getCaughtType().getTypePtr()->getPointeeCXXRecordDecl()->bases_begin() == nullptr){
cout << "This class is the base class" << endl;
}
else{
cout << "Base class caught : " << tryStmt->getHandler(i)->getCaughtType().getTypePtr()->getPointeeCXXRecordDecl()->bases_begin()->getType().getAsString() << endl;
}
cout << "\n \n END OF LOOP \n \n" << endl;
}
return true;
}
Outputs the following output for the example asked in the question:
Class caught: D
Base class caught: class B
END OF CONTROL
Class caught: B
This class is the base class
END OF CONTROL
source to share