我正在创建一个名为“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/