0

I am trying to define an overall class, call it "Command" which can take an "enum Action" that defines which command to run. I would like to have this class represent any possible command (store each command's variable) but I don't want to define a class per command that inherits from the general Command class.

For example, the class Command defines an "enum Action" that defines which command to run. If it is start, it stores an int and a char*, if it is something like "setResolution", it stores two ints: width and height.

I would like this class to be able to represent any command, but I am not sure what is the best OO way to achieve this please. My OO is very rusty and I can't seem to find a solution that doesn't involve inheritance. Thank you.

4

1 回答 1

2

您所描述的内容听起来很像使用std::function和的组合功能std::bind。使用这些创建一个可调用的函数对象,该对象存储需要传递的所有参数,同时允许您在不知道任何具体细节的情况下执行调用。它适用于成员函数和自由函数。您可以将您的Command类更改为描述需求的简单包装器。

下面的示例使用自由函数执行此操作。该类Command不关心参数或其类型。它只关心命令本身是如何分派的。

#include <iostream>
#include <functional>
#include <string>

class Command
{
public:
    Command(const std::string& name, const std::function<void()>& func)
        : name_(name), func_(func) {}

    Command(const Command& o) : name_(o.name_), func_(o.func_) {}

    void operator()()
    {
        std::cout << "executing " << name_ << std::endl;
        func_();
    };

    const std::string name() const { return name_; }

private:
    Command& operator=(const Command&);

    const std::string           name_;
    const std::function<void()> func_;
};

void start(int a, const char* b)
{
    std::cout << "start(" << a << "," << b << ")" << std::endl;
}
void setResolution(int a, int b)
{
    std::cout << "setResolution(" << a << "," << b << ")" << std::endl;
}

int main()
{
    Command start("start", std::bind(start, 1, "hello world"));
    Command setRes("setRes", std::bind(setResolution, 640, 480));

    start();
    setRes();
}
于 2013-07-02T19:55:26.943 回答