Yawin
Yawin

Reputation: 23

Error: non-static data member declared ‘auto’

I am making a class called "StateMachine" to make other classes that inherit that logic.

Trying to make the "State" structure store a pointer to the function to execute in that state, I have found myself needing to use lambda functions. However, I can't seem to declare an auto member inside a struct without it being "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 = "";
};

Example of use

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

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

The error

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

What can I do?

Upvotes: 2

Views: 1370

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

You could use std::function to simplify this.

#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});
    }
    //...

Upvotes: 1

Related Questions