Error: non-static data member declared ‘auto’

Error: non-static data member declared ‘auto’

我正在制作一个名为“StateMachine”的 class 来制作继承该逻辑的其他 classes。

试图让“状态”结构存储指向在该状态下执行的函数的指针,我发现自己需要使用 lambda 函数。但是,我似乎无法在结构内声明一个自动成员,除非它是“scatic const”。

statemachine.h

#include <vector>
#include <string>
#include <map>
using namespace std;

struct State
{
    string id;
    auto action;
    string next;

    State():id(""){}
    State(string _id, auto func, string n = ""):id(_id), action(func), next(n){}
};

class StateMachine
{
  protected:
    void addState(string id, auto func)
    {
      if(activeState == ""){activeState = id;}
      stateList.insert(pair<string, State>(id, State(id, func)));
    }

    void doAction()
    {
      if(stateList[activeState].action != nullptr)
      {
        (*stateList[activeState].action)();

        if(stateList[activeState].next != "")
        {
          activeState = stateList[activeState].next;
        }
      }
    }

    void setState(string state)
    {
      if(stateList.count(state) != 0)
      {
        activeState = state;
      }
    }

    string getState()
    {
      return activeState;
    }

  private:
    map<string, State> stateList;
    string activeState = "";
};

使用示例

class Player : public StateMachine
{
  public:
    Player()
    {
      addState("ST_SPAWN", [this]{this->OnSpawn();});
    }
    virtual ~Player(){}

    void OnSpawn()
    {
        //...
    }
};

错误

/home/yawin/Dokumentuak/Proyectos/C++/Dough/src/./include/interfaces/statemachine.h:34:10: error: non-static data member declared ‘auto’
     auto action;

我能做什么?

您可以使用 std::function 来简化它。

#include <functional>

struct State {
    string id;
    std::function<void()> action;
    string next;

    State(){id = "";}
    State(string _id, std::function<void()> func, string n = "") :
        id(_id), action(func), next(n) {}
};
class StateMachine {
    //...
    void addState(string id, std::function<void()> func) {
        if(activeState == "") activeState = id;
        stateList.emplace(id, State{id, func});
    }
    //...