Search code examples
c++functionoopfunction-object

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


I'm trying to create a generic menu, so I came with the idea of creating a menu with options, and each option in the menu will have a label, key to execute, and an Action.

The Action is template class simply stores a function and runs it when I need it by the call to execute().

My problem is that for each Action, I need to create a new class - function object. It feels wrong.

My goal is to be able to call a function anytime in code by calling Action and not directly to it. And not the way we did in C (as using type: void(*func)() for example ).

I'm new at CPP and I wonder what I should do because it doesn't look right. Of course, correct me if I'm wrong.

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 ...
};

the main is very basic to illustrate how I want it to works

 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;
 }

Solution

  • Using Command Design Pattern is a great option and answer my needs.