So, I thought I had understood member function pointers and std::fuction, but sadly this is not the case yet.
I have the following code - its some early bits of a state machine, but I am struggling. let me paste the code:
#include <iostream>
#include <functional>
#include <map>
//forward decls
class state_t;
enum event_t
{
ev_start = 0,
ev_middle,
ev_end
};
struct transition_t
{
//std::function<bool()> guard_function();
std::function<bool()> guard_function;
state_t *p_next_state;
};
class state_t
{
public:
std::map<event_t, transition_t> transitions;
bool some_guard()
{
std::cout << "check the guard condition - all is well" << std::endl;
return true;
}
};
int main()
{
std::cout << "Hello World!" << std::endl;
state_t s1;
state_t s2;
// Setup transitions
s1.transitions[event_t::ev_start] = transition_t{s1::some_guard, &s2};
s1.transitions[event_t::ev_middle] = transition_t{nullptr, &s2}; // no guard
event_t test_event = event_t::ev_start;
auto trans = s1.transitions.find(event_t::ev_start);
if (trans != s1.transitions.end())
{
// change state - TBD
std::cout << "changingn state" << std::endl;
}
return 0;
}
Ok, so:
event_t
is just some enumstransition_t
is meant to contain a pointer to some guard function that returns a bool and a pointer to the next state.state_t
has a map of events and transitions and contains some guard functions that can be stored in the transition_t.
So in main() I am trying to construct some states...
s1.transitions[event_t::ev_start] = transition_t{s1::some_guard, &s2}; // <--- this line fails
s1.transitions[event_t::ev_middle] = transition_t{nullptr, &s2}; // <--- this line works (not so surprised)
But I can't quite figure out how to sort this. I have done this in the past with lambdas and templates... but I really wanted to give std::function a go to see if its better / easier...
Any pointers/guides what to do here would be welcome even if its using lambdas :), but I would prefer to get std::function working