jeudi 27 avril 2017

Is that possible to know all the name of derived classes?

Suppose we have a base class and a bunch of derived classes. Is there any way or mechanism to know all the derived class names programmatically?

Maybe reflection is a good idea, but it's not available on C++. I suppose there will be some kind of template that can finish this job during compilation.

class Base{
public:
    virtual void print(){
        // This function should print all the names of derived class.
    }
    virtual Base* getInstance(string class_name){
        // This function should return an instance related to the class name.
    }
};

class Derived_1 : public Base{ // Suppose we have 100 Derived_X classes, 
                 // so we don't want to add its name to a list manually.
};

int main(){
    Base base;
    base.print(); // This should print the name of all the derived class.
    base.getInstance("Derived_1"); // This should return an instance of Derived_1
    return 0;
}





Aucun commentaire:

Enregistrer un commentaire