c++ - 错误:非静态数据成员声明了 ‘auto’

标签 c++ function lambda non-static

我正在创建一个名为“StateMachine”的类,以使其他类继承该逻辑。
试图使“状态”结构存储指向要在该状态下执行的函数的指针,我发现自己需要使用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});
    }
    //...

关于c++ - 错误:非静态数据成员声明了 ‘auto’,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64098048/

相关文章:

c++ - 监控程序读/写路径的程序?

c++ - 为什么函数参数中的 const 限定符用于重载解析?

C 函数内的 block ?

Python - 何时创建类以及何时创建函数

haskell - 共享部分应用功能

c++ - While 循环终止问题?

c++ - 有没有简单的方法将 xlnt 包含到 Ubuntu 上的 Visual Studio Code 中?

function - 为什么追加函数调用时函数执行顺序似乎颠倒了?

Java 8 Streams 取字符串行的总和

java - 使用 Lambda 表达式参数化的 Vert.x 日志语句