I made a class and a struct.
The class is named Learning and the struct is named Action.
My Action constructor takes one parameter: object's function, and the function is a std::function<int(int)>.
This is my Action struct:
typedef std::function<int(int)> func;
struct Action {
// constructor
Action(func);
/// methods
/// operators
int operator()(int x);
/// members
func f;
};
Action(func f) {this->f = f; }
My Action struct is used by my Learning class by calling this function:
class Learning
{
public:
void addAction(Action);
Action getAction(int idx);
private:
std::vector<Action> actions;
};
void Learning::addAction(Action act)
{
actions.push_back(act);
}
int Learning::getAction(int idx)
{
return actions[idx];
}
int main(){
Learning robot;
robot.addAction(Action([](int y) ->int{return y++; }));
std::cout << robot.getAction(0)(0) << std::endl;
return 0;
}
Where the Action is saved inside an actions vector in my Learning class:
The method addAction() adds the created Action object into my actions vector. another method 'getAction(idx)' is used to call one action from action vector.
I used a lambda expression as the parameter because it looks cleaner.
But when I call robot.getAction(0)(0), or actions[0](0) inside the class, I get an exception:
Unhandled exception at 0x00007FFA4DE44F69 in RL_Q.exe: Microsoft C++ exception: std::bad_function_call at memory location 0x000000C09A7BE4C0.
When I debug this, my function f is empty after I instantiate my Action object with given parameters.
How do I solve this?