存储函数而不直接以 C++ 方式创建新的函数对象

store a function without directly creating new function objects in C++ way

我正在尝试创建一个通用菜单,所以我想到了创建一个带有选项的菜单,菜单中的每个选项都有一个标签、执行键和一个操作。

Action 是模板 class 只是存储一个函数并在我需要时通过调用 execute() 来运行它。

我的问题是,对于每个 Action,我都需要创建一个新的 class - 函数对象。感觉不对。

我的目标是能够通过调用 Action 而不是直接调用它来在代码中随时调用函数。 不是 我们在 C 中所做的方式(例如使用类型:void(*func)())。

我是 CPP 的新手,我想知道我应该怎么做,因为它看起来不对。 当然,如果我错了,请指正。

class BaseAction
{
public:
    virtual bool Execute() const = 0;
    virtual ~BaseAction() {}
};

template<class Func>
class Action : public BaseAction
{
public:
    Action() : function() {}

    bool Execute() const override { return function(); }

private:
    Func function;
};

struct CommandManager
{
    struct Write
    {
        bool operator()() const
        {
            // code ...
            return true;
        }
    };

    struct Read
    {
        bool operator()() const
        {
            // code ...
            return true;
        }
    };

    // More function objects ...
};

主要内容非常基础,可以说明我希望它如何工作

 int main()
 {
     Action<CommandManager::Write> writeCommand; // store the function Write
     Action<CommandManager::Read>  readCommand;  // store the function Read
     int input;
     std::cin >> input;

     BaseAction* action;
     if (input)
         action = &readCommand;
     else
         action = &writeCommand;

     action->Execute(); // Run user requested function

     return 0;
 }

使用命令设计模式是一个很好的选择,可以满足我的需求。