mardi 9 novembre 2021

How to get all child objects of a class

Is it possible to retrieve a list of child objects (of a cetain type) of an object ?

For example in this code I have an App with several available Commands. A function print all availible commands this way the user knows what he can do.
I want to iterate over each object of type Command found in App to print his doc, this way the doc updates itself automatically every time a Command is added in App.

class Command {
public:
    std::string Name;
    std::string Description;
    virtual void Compute() = 0;
};

class StartCommand : public Command {
    std::string Name = "start";
    std::string Description = "Start the process";
    virtual void Compute() {
        // Code to start the process
    }
};

class StopCommand : public Command {
    std::string Name = "stop";
    std::string Description = "Stop the process";
    virtual void Compute() {
        // Code to stop the process
    }
};

class App {
public:
    StartCommand StartCommand;
    StopCommand StopCommand;

    void PrintAvailibleCommands() {
        std::cout << "All availible commands are: " << std::endl;
        for (Command command : this.GetObjects<Command>()) {
            std::cout << command.Name << ": " << command.Description << std::endl;
        }
    }
};

It's the this.GetObjects<Command>() function which does not exist and which I would like to implement.

Du you have an idea ?





Aucun commentaire:

Enregistrer un commentaire