How to get the base class from this example with C

2019-02-19 22:23发布

问题:

Here is a very basic sample of code, 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 am able to get the CXXRecordDecl of class B and class D, in handlers (I can get them from the getCaughtType method in CXXCatchStmt class).

What I would like to do is to be able to access CXXRecordDecl of class B from class D, since we have class D : public B.

I have tried the following methods available in class CXXRecordDecl on my CXXRecordDecl of class D:

  • getCanonicalDecl() : returns class D
  • getInstantiatedFromMemberClass() : returns nullptr
  • getDefinition() : returns class D

I'm out of ideas right now. Does someone have an idea ?

回答1:

Here is the implementation of the answer given by Joachim Pileborg in 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; 
}

Yields the following output for the example given in the question :

Class caught : D

Base class caught : class B

END OF LOOP

Class caught : B

This class is the base class

END OF LOOP



标签: c++ clang