0

in my first attempt to implement the Command Pattern, I written this code:

struct JSONObject {
  std::string json;
  JSONObject() : json("") {}
};

struct BaseCommand {
  std::string label;
  std::shared_ptr<JSONObject> jp;

  virtual ~BaseCommand() = default;
  virtual std::shared_ptr<JSONObject> execute() = 0;
};

struct DerivedCommand : public BaseCommand {
  int intParameter;

  DerivedCommand(std::string label_, int x_) : intParameter(x_) {
    label = label_;
    jp = std::make_shared<JSONObject>();
  }

  std::shared_ptr<JSONObject> execute() {
    ++intParameter;
    jp->json =
        "{\"cmd\":\"Derived\", \"value\":" + std::to_string(intParameter) + "}";
    return jp;
  }
};

int main() {
  std::stack<std::shared_ptr<BaseCommand>> comStack;
  auto cmd = std::make_shared<DerivedCommand>("Derived", 41);
  comStack.push(cmd);
  auto topCmd = comStack.top();
  std::cout << topCmd->label << std::endl;
  auto json = topCmd->execute();
  std::cout << json->json << std::endl;

  if (topCmd->label.compare("Derived") == 0) {
    // std::shared_ptr<commandtest::DerivedCommand> derCmd =
    // dynamic_cast<std::shared_ptr<commandtest::DerivedCommand>>topCmd;
    // std::cout << derCmd->intParameter << std::endl;
  }

  return 0;
}

This code compiles and runs. However, I may want to cast the command back to it's correct type (e.g. DerivedCommand), depending on the stored label (see commented out part). Of course I tried Google and reading up on it (e.g. C++ cast to derived class), but can't make it work.

Thank you in advance!

P.S.: If you have any other advice on how to improve this, I would also appreciate it.

Markstar
  • 639
  • 9
  • 24

0 Answers0